pi-session-subagents 0.0.0-stage → 0.1.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 +16 -0
- package/LICENSE +21 -0
- package/README.md +216 -2
- package/package.json +61 -5
- package/src/copy.ts +79 -0
- package/src/index.ts +63 -0
- package/src/model-resolver.ts +43 -0
- package/src/report.ts +143 -0
- package/src/roster.ts +198 -0
- package/src/text.ts +77 -0
- package/src/tools.ts +361 -0
- package/src/ui/conversation-viewer.ts +408 -0
- package/src/ui/widget.ts +119 -0
- package/src/worker-session.ts +146 -0
- package/src/worker.ts +242 -0
package/src/worker.ts
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { AgentSession, PromptOptions } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { LATE_STEER_TURN_MESSAGE, timeoutMessage } from "./copy";
|
|
4
|
+
import { formatDuration, lastLine, messageText, summarizeToolArgs } from "./text";
|
|
5
|
+
import { closeWorkerSession } from "./worker-session";
|
|
6
|
+
|
|
7
|
+
export type WorkerStatus = "idle" | "running" | "done" | "error" | "stopped";
|
|
8
|
+
|
|
9
|
+
export interface WorkerInfo {
|
|
10
|
+
modelLabel: string;
|
|
11
|
+
cwd: string;
|
|
12
|
+
requestedTools: string[];
|
|
13
|
+
warnings: string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface RunStats {
|
|
17
|
+
turns: number;
|
|
18
|
+
toolUses: number;
|
|
19
|
+
tokens: number;
|
|
20
|
+
durationMs: number;
|
|
21
|
+
outcome: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
type PromptDisposition = Parameters<NonNullable<PromptOptions["preflightResult"]>>[0];
|
|
25
|
+
|
|
26
|
+
interface Run {
|
|
27
|
+
id: number;
|
|
28
|
+
task: string;
|
|
29
|
+
startedAt: number;
|
|
30
|
+
lastEntryBeforeRun: string | null;
|
|
31
|
+
controller: AbortController;
|
|
32
|
+
submissions: Set<Promise<void>>;
|
|
33
|
+
submitError?: unknown;
|
|
34
|
+
done?: Promise<void>;
|
|
35
|
+
endedAt?: number;
|
|
36
|
+
error?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let lastRunIdAcrossWorkers = 0;
|
|
40
|
+
|
|
41
|
+
export class Worker {
|
|
42
|
+
readonly createdAt = Date.now();
|
|
43
|
+
private run: Run | undefined;
|
|
44
|
+
private closing: Promise<void> | undefined;
|
|
45
|
+
|
|
46
|
+
constructor(
|
|
47
|
+
readonly name: string,
|
|
48
|
+
readonly session: AgentSession,
|
|
49
|
+
readonly info: WorkerInfo,
|
|
50
|
+
private readonly onRunEnd: (worker: Worker) => void,
|
|
51
|
+
) {}
|
|
52
|
+
|
|
53
|
+
get status(): WorkerStatus {
|
|
54
|
+
if (this.closing) return "stopped";
|
|
55
|
+
if (!this.run) return "idle";
|
|
56
|
+
if (this.run.endedAt === undefined) return "running";
|
|
57
|
+
return this.run.error ? "error" : "done";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
get task(): string {
|
|
61
|
+
return this.run?.task ?? "";
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
get runId(): number {
|
|
65
|
+
return this.run?.id ?? 0;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
get error(): string {
|
|
69
|
+
return this.run?.error ?? "";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
settled(): Promise<void> {
|
|
73
|
+
return this.run?.done ?? Promise.resolve();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
stats(): RunStats {
|
|
77
|
+
const run = this.run;
|
|
78
|
+
if (!run) return { turns: 0, toolUses: 0, tokens: 0, durationMs: 0, outcome: "" };
|
|
79
|
+
const messages = this.runMessages(run);
|
|
80
|
+
let toolUses = 0;
|
|
81
|
+
let tokens = 0;
|
|
82
|
+
for (const message of messages) {
|
|
83
|
+
toolUses += message.content.filter((part) => part.type === "toolCall").length;
|
|
84
|
+
const usage = message.usage;
|
|
85
|
+
tokens += (usage?.input ?? 0) + (usage?.output ?? 0) + (usage?.cacheRead ?? 0) + (usage?.cacheWrite ?? 0);
|
|
86
|
+
}
|
|
87
|
+
const outcome = messageText(messages.findLast((message) => messageText(message)));
|
|
88
|
+
return {
|
|
89
|
+
turns: messages.length,
|
|
90
|
+
toolUses,
|
|
91
|
+
tokens,
|
|
92
|
+
durationMs: (run.endedAt ?? Date.now()) - run.startedAt,
|
|
93
|
+
outcome,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
activity(): string {
|
|
98
|
+
if (this.status !== "running") return this.error || lastLine(this.stats().outcome);
|
|
99
|
+
const state = this.session.state;
|
|
100
|
+
const calls =
|
|
101
|
+
lastAssistant(state.messages)?.content.flatMap((part) =>
|
|
102
|
+
part.type === "toolCall" && state.pendingToolCalls.has(part.id)
|
|
103
|
+
? [`${part.name} ${summarizeToolArgs(part.arguments)}`.trim()]
|
|
104
|
+
: [],
|
|
105
|
+
) ?? [];
|
|
106
|
+
if (calls.length) return calls.join(", ");
|
|
107
|
+
const streaming =
|
|
108
|
+
state.streamingMessage?.role === "assistant" ? lastLine(messageText(state.streamingMessage)) : "";
|
|
109
|
+
return streaming || "thinking…";
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
capabilities(): { enabledTools: string[]; callableTools: string[]; missingTools: string[]; warnings: string[] } {
|
|
113
|
+
const enabledTools = this.session.getActiveToolNames();
|
|
114
|
+
return {
|
|
115
|
+
enabledTools,
|
|
116
|
+
callableTools: this.session.getCallableToolNames(),
|
|
117
|
+
missingTools: this.info.requestedTools.filter((name) => !enabledTools.includes(name)),
|
|
118
|
+
warnings: this.info.warnings,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
start(task: string, timeoutMs?: number): void {
|
|
123
|
+
if (this.closing) throw new Error(`${this.name} has been stopped.`);
|
|
124
|
+
const run: Run = {
|
|
125
|
+
id: ++lastRunIdAcrossWorkers,
|
|
126
|
+
task,
|
|
127
|
+
startedAt: Date.now(),
|
|
128
|
+
lastEntryBeforeRun: this.session.sessionManager.getLeafId(),
|
|
129
|
+
controller: new AbortController(),
|
|
130
|
+
submissions: new Set(),
|
|
131
|
+
};
|
|
132
|
+
this.run = run;
|
|
133
|
+
run.done = this.execute(run, timeoutMs);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async steer(text: string): Promise<"steer" | "handled"> {
|
|
137
|
+
const run = this.run;
|
|
138
|
+
if (!run || run.endedAt !== undefined) throw new Error(`${this.name} is not running.`);
|
|
139
|
+
return (await this.promptUntilAccepted(run, text)) === "handled" ? "handled" : "steer";
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
close(): Promise<void> {
|
|
143
|
+
this.closing ??= (async () => {
|
|
144
|
+
const run = this.run;
|
|
145
|
+
if (run && run.endedAt === undefined) this.cancel(run, new Error("Stopped."));
|
|
146
|
+
await run?.done;
|
|
147
|
+
await closeWorkerSession(this.session);
|
|
148
|
+
})();
|
|
149
|
+
return this.closing;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private async execute(run: Run, timeoutMs?: number): Promise<void> {
|
|
153
|
+
const timer = timeoutMs
|
|
154
|
+
? setTimeout(() => this.cancel(run, new Error(timeoutMessage(formatDuration(timeoutMs)))), timeoutMs)
|
|
155
|
+
: undefined;
|
|
156
|
+
let failure: unknown;
|
|
157
|
+
try {
|
|
158
|
+
await this.promptUntilAccepted(run, run.task);
|
|
159
|
+
await this.finishAcceptedPromptsAndLateSteers(run);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
failure = error;
|
|
162
|
+
}
|
|
163
|
+
clearTimeout(timer);
|
|
164
|
+
if (run.controller.signal.aborted) {
|
|
165
|
+
this.session.clearQueue();
|
|
166
|
+
failure = run.controller.signal.reason;
|
|
167
|
+
}
|
|
168
|
+
failure ??= run.submitError;
|
|
169
|
+
run.endedAt = Date.now();
|
|
170
|
+
run.error = failure !== undefined ? errorText(failure) : lastTurnError(this.runMessages(run));
|
|
171
|
+
if (!this.closing) this.onRunEnd(this);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
private async finishAcceptedPromptsAndLateSteers(run: Run): Promise<void> {
|
|
175
|
+
while (true) {
|
|
176
|
+
if (run.submissions.size > 0) {
|
|
177
|
+
await Promise.all(run.submissions);
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (run.controller.signal.aborted || run.submitError !== undefined || this.session.pendingMessageCount === 0)
|
|
181
|
+
return;
|
|
182
|
+
// A steer accepted after the last turn's queue check waits for a turn that never comes, so start one.
|
|
183
|
+
await this.session.sendCustomMessage(
|
|
184
|
+
{ customType: "subagent-late-steer", content: LATE_STEER_TURN_MESSAGE, display: false },
|
|
185
|
+
{ triggerTurn: true },
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private promptUntilAccepted(run: Run, text: string): Promise<PromptDisposition> {
|
|
191
|
+
return new Promise((resolve, reject) => {
|
|
192
|
+
let accepted = false;
|
|
193
|
+
const work: Promise<void> = this.session
|
|
194
|
+
.prompt(text, {
|
|
195
|
+
streamingBehavior: "steer",
|
|
196
|
+
preflightResult: (disposition) => {
|
|
197
|
+
accepted = true;
|
|
198
|
+
if (disposition === "started" && run.controller.signal.aborted) void this.session.abort();
|
|
199
|
+
resolve(disposition);
|
|
200
|
+
},
|
|
201
|
+
})
|
|
202
|
+
.then(
|
|
203
|
+
() => resolve("queued"),
|
|
204
|
+
(error) => {
|
|
205
|
+
if (!accepted) reject(error);
|
|
206
|
+
else run.submitError ??= error;
|
|
207
|
+
},
|
|
208
|
+
)
|
|
209
|
+
.finally(() => run.submissions.delete(work));
|
|
210
|
+
run.submissions.add(work);
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private cancel(run: Run, reason: Error): void {
|
|
215
|
+
if (run.controller.signal.aborted) return;
|
|
216
|
+
run.controller.abort(reason);
|
|
217
|
+
void this.session.abort();
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private runMessages(run: Run): AssistantMessage[] {
|
|
221
|
+
const branch = this.session.sessionManager.getBranch();
|
|
222
|
+
const start = branch.findIndex((entry) => entry.id === run.lastEntryBeforeRun) + 1;
|
|
223
|
+
return branch
|
|
224
|
+
.slice(start)
|
|
225
|
+
.flatMap((entry) => (entry.type === "message" && entry.message.role === "assistant" ? [entry.message] : []));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function lastAssistant(messages: readonly { role: string }[]): AssistantMessage | undefined {
|
|
230
|
+
return messages.findLast((message): message is AssistantMessage => message.role === "assistant");
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function lastTurnError(messages: AssistantMessage[]): string {
|
|
234
|
+
const last = messages.at(-1);
|
|
235
|
+
if (last?.stopReason === "error") return last.errorMessage || "Model request failed.";
|
|
236
|
+
if (last?.stopReason === "aborted") return last.errorMessage || "Run was aborted.";
|
|
237
|
+
return "";
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function errorText(error: unknown): string {
|
|
241
|
+
return error instanceof Error ? error.message : String(error);
|
|
242
|
+
}
|