pi-herdr-subagents-lite 0.7.2 → 0.9.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.
@@ -0,0 +1,236 @@
1
+ import { mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+
4
+ export type TurnOutcome = "done" | "error" | "aborted" | "quit";
5
+
6
+ export interface Turn {
7
+ turn: number;
8
+ outcome: TurnOutcome;
9
+ stopReason: string;
10
+ errorMessage?: string;
11
+ text?: string;
12
+ children: number;
13
+ at: number;
14
+ }
15
+
16
+ export interface TurnInput {
17
+ stopReason: string | undefined;
18
+ pendingToolCall: boolean;
19
+ aborted: boolean;
20
+ errorMessage?: string;
21
+ }
22
+
23
+ export interface TurnVerdict {
24
+ outcome: TurnOutcome;
25
+ errorMessage?: string;
26
+ }
27
+
28
+ export interface TurnEntry {
29
+ type?: string;
30
+ message?: {
31
+ role?: string;
32
+ content?: unknown;
33
+ stopReason?: string;
34
+ errorMessage?: string;
35
+ };
36
+ }
37
+
38
+ export interface TurnSlice {
39
+ found: boolean;
40
+ stopReason: string | undefined;
41
+ errorMessage: string | undefined;
42
+ pendingToolCall: boolean;
43
+ text: string | null;
44
+ }
45
+
46
+ const OUTCOMES: ReadonlySet<string> = new Set(["done", "error", "aborted", "quit"]);
47
+ const TRUNCATED = "答案在输出上限处被截断,不是完整结果。";
48
+ const NO_MESSAGE = "这一轮以错误结束,没有错误信息。";
49
+ const TURN_FILE = /^\d{6}\.json$/;
50
+
51
+ function textOf(content: unknown): string | null {
52
+ if (!Array.isArray(content)) {
53
+ return null;
54
+ }
55
+ const text = content
56
+ .filter((block): block is { type: "text"; text: string } => {
57
+ if (typeof block !== "object" || block === null) {
58
+ return false;
59
+ }
60
+ const candidate = block as { type?: unknown; text?: unknown };
61
+ return candidate.type === "text" && typeof candidate.text === "string";
62
+ })
63
+ .map((block) => block.text)
64
+ .filter((line) => line.trim() !== "")
65
+ .join("\n")
66
+ .trim();
67
+ return text === "" ? null : text;
68
+ }
69
+
70
+ function hasToolCall(content: unknown): boolean {
71
+ if (!Array.isArray(content)) {
72
+ return false;
73
+ }
74
+ return content.some((block) => {
75
+ if (typeof block !== "object" || block === null) {
76
+ return false;
77
+ }
78
+ const candidate = block as { type?: unknown; name?: unknown };
79
+ return candidate.type === "toolCall" && typeof candidate.name === "string";
80
+ });
81
+ }
82
+
83
+ // 只取最后一条 user 消息之后的内容:/tree、压缩、续跑都不能把旧答案算进这一轮。
84
+ export function lastTurnOf(entries: TurnEntry[]): TurnSlice {
85
+ let start = 0;
86
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
87
+ const entry = entries[index];
88
+ if (entry?.type === "message" && entry.message?.role === "user") {
89
+ start = index + 1;
90
+ break;
91
+ }
92
+ }
93
+ for (let index = entries.length - 1; index >= start; index -= 1) {
94
+ const entry = entries[index];
95
+ if (entry?.type !== "message" || entry.message?.role !== "assistant") {
96
+ continue;
97
+ }
98
+ const content = entry.message.content;
99
+ return {
100
+ found: true,
101
+ stopReason: entry.message.stopReason,
102
+ errorMessage: entry.message.errorMessage,
103
+ pendingToolCall: hasToolCall(content),
104
+ text: textOf(content),
105
+ };
106
+ }
107
+ return { found: false, stopReason: undefined, errorMessage: undefined, pendingToolCall: false, text: null };
108
+ }
109
+
110
+ // 只判定这一轮怎么结束,不判定子代理之后该干什么。
111
+ export function classifyTurn(input: TurnInput): TurnVerdict {
112
+ if (input.aborted || input.pendingToolCall) {
113
+ return { outcome: "aborted" };
114
+ }
115
+ switch (input.stopReason) {
116
+ case undefined:
117
+ case "stop":
118
+ return { outcome: "done" };
119
+ case "aborted":
120
+ case "toolUse":
121
+ return { outcome: "aborted" };
122
+ case "length":
123
+ return { outcome: "error", errorMessage: TRUNCATED };
124
+ case "error":
125
+ return { outcome: "error", errorMessage: input.errorMessage ?? NO_MESSAGE };
126
+ default:
127
+ return { outcome: "error", errorMessage: `这一轮的结束原因未识别:${input.stopReason}。` };
128
+ }
129
+ }
130
+
131
+ export function turnsDir(runBase: string): string {
132
+ return `${runBase}.turns`;
133
+ }
134
+
135
+ export function turnFile(runBase: string, turn: number): string {
136
+ return join(turnsDir(runBase), `${String(turn).padStart(6, "0")}.json`);
137
+ }
138
+
139
+ function writeAtomic(file: string, text: string): void {
140
+ mkdirSync(dirname(file), { recursive: true });
141
+ const temp = `${file}.tmp`;
142
+ writeFileSync(temp, text);
143
+ renameSync(temp, file);
144
+ }
145
+
146
+ export function writeTurn(runBase: string, turn: Turn): string {
147
+ const file = turnFile(runBase, turn.turn);
148
+ writeAtomic(file, JSON.stringify(turn));
149
+ return file;
150
+ }
151
+
152
+ function optionalString(value: unknown): string | undefined {
153
+ return typeof value === "string" ? value : undefined;
154
+ }
155
+
156
+ export function readTurn(file: string): Turn | null {
157
+ let raw: string;
158
+ try {
159
+ raw = readFileSync(file, "utf8");
160
+ } catch {
161
+ return null;
162
+ }
163
+ let parsed: unknown;
164
+ try {
165
+ parsed = JSON.parse(raw);
166
+ } catch {
167
+ return null;
168
+ }
169
+ if (typeof parsed !== "object" || parsed === null) {
170
+ return null;
171
+ }
172
+ const turn = parsed as Partial<Turn>;
173
+ if (
174
+ typeof turn.turn !== "number" ||
175
+ typeof turn.stopReason !== "string" ||
176
+ typeof turn.children !== "number" ||
177
+ typeof turn.at !== "number" ||
178
+ typeof turn.outcome !== "string" ||
179
+ !OUTCOMES.has(turn.outcome)
180
+ ) {
181
+ return null;
182
+ }
183
+ const errorMessage = optionalString(turn.errorMessage);
184
+ const text = optionalString(turn.text);
185
+ return {
186
+ turn: turn.turn,
187
+ outcome: turn.outcome as TurnOutcome,
188
+ stopReason: turn.stopReason,
189
+ children: turn.children,
190
+ at: turn.at,
191
+ ...(errorMessage === undefined ? {} : { errorMessage }),
192
+ ...(text === undefined ? {} : { text }),
193
+ };
194
+ }
195
+
196
+ export function listTurns(runBase: string): string[] {
197
+ let names: string[];
198
+ try {
199
+ names = readdirSync(turnsDir(runBase));
200
+ } catch {
201
+ return [];
202
+ }
203
+ return names
204
+ .filter((name) => TURN_FILE.test(name))
205
+ .sort()
206
+ .map((name) => join(turnsDir(runBase), name));
207
+ }
208
+
209
+ export function removeTurn(file: string): void {
210
+ try {
211
+ unlinkSync(file);
212
+ } catch (error) {
213
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
214
+ throw error;
215
+ }
216
+ }
217
+ }
218
+
219
+ // 子代理是唯一写入者,所以不需要锁。
220
+ export function nextTurn(runBase: string): number {
221
+ const file = `${runBase}.turn`;
222
+ let current = 0;
223
+ try {
224
+ const parsed = Number.parseInt(readFileSync(file, "utf8").trim(), 10);
225
+ if (Number.isFinite(parsed) && parsed > 0) {
226
+ current = parsed;
227
+ }
228
+ } catch (error) {
229
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
230
+ throw error;
231
+ }
232
+ }
233
+ const next = current + 1;
234
+ writeAtomic(file, String(next));
235
+ return next;
236
+ }
@@ -1,35 +0,0 @@
1
- import { inboxCount } from "../inbox/index.ts";
2
- import { AUTO_EXIT_ENV } from "../run/index.ts";
3
- import type { ExtensionRegistrar } from "./index.ts";
4
-
5
- export function watchAutoExit(pi: ExtensionRegistrar): { reset(): void } {
6
- let openPrompts = 0;
7
- let exiting = false;
8
-
9
- pi.on("ui_prompt_start", () => {
10
- openPrompts += 1;
11
- });
12
-
13
- pi.on("ui_prompt_end", () => {
14
- openPrompts = Math.max(0, openPrompts - 1);
15
- });
16
-
17
- pi.on("agent_settled", (_event, ctx) => {
18
- if (exiting || process.env[AUTO_EXIT_ENV] !== "1" || openPrompts > 0) {
19
- return;
20
- }
21
- const sessionFile = ctx.sessionManager.getSessionFile();
22
- if (!sessionFile || inboxCount(sessionFile) > 0) {
23
- return;
24
- }
25
- exiting = true;
26
- ctx.shutdown();
27
- });
28
-
29
- return {
30
- reset() {
31
- openPrompts = 0;
32
- exiting = false;
33
- },
34
- };
35
- }
@@ -1,84 +0,0 @@
1
- import type { ExitReceipt } from "../session-file/index.ts";
2
- import { closeTab, shouldClose } from "./close.ts";
3
- import type { RunResult } from "./result.ts";
4
- import { doneResult, unknownResult } from "./result.ts";
5
- import type { RunRecord, RunState } from "./state.ts";
6
-
7
- const POLL_FAILURE_LIMIT = 3;
8
- const READ_ATTEMPTS = 3;
9
- const READ_RETRY_DELAY_MS = 200;
10
-
11
- export async function recordFailure(state: RunState, run: RunRecord): Promise<void> {
12
- if (!run.live) {
13
- return;
14
- }
15
- run.pollFailures += 1;
16
- if (run.pollFailures >= POLL_FAILURE_LIMIT) {
17
- await finish(state, run, unknownResult(run, "poll_failed"));
18
- }
19
- }
20
-
21
- export async function readResult(state: RunState, run: RunRecord, seq: number, attempt: number): Promise<void> {
22
- run.read = undefined;
23
- if (!run.live) {
24
- return;
25
- }
26
-
27
- const snapshot = state.readLastAssistant(run.sessionFile);
28
- if (snapshot.pendingToolCall || snapshot.empty) {
29
- return;
30
- }
31
- if (snapshot.text !== null) {
32
- run.lastHandledSeq = seq;
33
- if (snapshot.text === run.lastDeliveredText) {
34
- return;
35
- }
36
- run.lastDeliveredText = snapshot.text;
37
- await finish(state, run, await doneResult(run, snapshot.text, state.maxResultChars));
38
- return;
39
- }
40
-
41
- if (attempt >= READ_ATTEMPTS) {
42
- run.lastHandledSeq = seq;
43
- if (run.lastDeliveredText === null) {
44
- await finish(state, run, unknownResult(run, "no_result"));
45
- }
46
- return;
47
- }
48
-
49
- run.read = { seq, attempt, at: state.now() + READ_RETRY_DELAY_MS };
50
- }
51
-
52
- export async function exited(state: RunState, run: RunRecord, receipt: ExitReceipt | null): Promise<void> {
53
- if (!run.live) {
54
- return;
55
- }
56
- const tail = state.readLastAssistant(run.sessionFile);
57
- const text = tail.pendingToolCall ? null : tail.text;
58
- if (text !== null) {
59
- if (text !== run.lastDeliveredText) {
60
- run.lastDeliveredText = text;
61
- await finish(state, run, await doneResult(run, text, state.maxResultChars));
62
- }
63
- } else if (run.lastDeliveredText === null) {
64
- const reason = receipt === null ? "pane_exited" : "quitted";
65
- await finish(state, run, unknownResult(run, reason));
66
- }
67
- state.settle(run);
68
- }
69
-
70
- async function finish(state: RunState, run: RunRecord, result: RunResult): Promise<void> {
71
- await state.results?.push(result);
72
- if (shouldClose(run, result)) {
73
- try {
74
- await closeTab(state, run);
75
- } catch {
76
- await state.results?.push(unknownResult(run, "close_failed"));
77
- }
78
- state.settle(run);
79
- return;
80
- }
81
- if (result.state !== "done") {
82
- state.settle(run);
83
- }
84
- }
package/src/run/poll.ts DELETED
@@ -1,127 +0,0 @@
1
- import type { AgentEntry } from "../herdr/index.ts";
2
- import { findAgent } from "./find.ts";
3
- import { exited, readResult, recordFailure } from "./poll-result.ts";
4
- import type { RunRecord, RunState } from "./state.ts";
5
-
6
- const ACTIVITY_WINDOW_MS = 30_000;
7
- const BUSY_STATUSES = new Set(["working", "blocked", "unknown"]);
8
- // 被杀死的子代理既不写回执,pane 也不会消失:这是唯一需要时限的死亡判定。
9
- const LOST_CHILD_MS = 10_000;
10
-
11
- // 不排 0 延迟:首拍太早只会多一次 list。
12
- export function wake(state: RunState): void {
13
- state.activeUntil = state.now() + ACTIVITY_WINDOW_MS;
14
- reschedule(state, state.pollIntervalMs);
15
- }
16
-
17
- export function stopPoll(state: RunState): void {
18
- if (state.pollTimer !== undefined) {
19
- clearTimeout(state.pollTimer);
20
- state.pollTimer = undefined;
21
- }
22
- }
23
-
24
- function reschedule(state: RunState, delayMs: number): void {
25
- stopPoll(state);
26
- if (state.stopped) {
27
- return;
28
- }
29
- state.pollTimer = setTimeout(() => void tick(state), delayMs);
30
- state.pollTimer.unref?.();
31
- }
32
-
33
- // 只读 state:投递链抛错时也要能排出下一拍。
34
- function plan(state: RunState): number | undefined {
35
- const live = state.runs.filter((run) => run.live);
36
- if (live.length === 0) {
37
- return undefined;
38
- }
39
- const now = state.now();
40
- let retry: number | undefined;
41
- for (const run of live) {
42
- if (run.read === undefined) {
43
- continue;
44
- }
45
- const delay = Math.max(0, run.read.at - now);
46
- retry = retry === undefined ? delay : Math.min(retry, delay);
47
- }
48
- if (retry !== undefined) {
49
- return retry;
50
- }
51
- const busy = now < state.activeUntil || live.some((run) => run.absentSince !== undefined || run.busy);
52
- return busy ? state.pollIntervalMs : state.idlePollIntervalMs;
53
- }
54
-
55
- async function tick(state: RunState): Promise<void> {
56
- state.pollTimer = undefined;
57
- state.pollBusy = true;
58
- try {
59
- await pollRuns(state);
60
- } finally {
61
- state.pollBusy = false;
62
- const delay = plan(state);
63
- if (delay !== undefined) {
64
- reschedule(state, delay);
65
- }
66
- }
67
- }
68
-
69
- async function pollRun(state: RunState, agents: AgentEntry[], run: RunRecord): Promise<void> {
70
- const agent = findAgent(agents, run);
71
- if (!agent) {
72
- await missing(state, run);
73
- return;
74
- }
75
- run.busy = BUSY_STATUSES.has(agent.status);
76
- run.absentSince = undefined;
77
- run.pollFailures = 0;
78
- if (run.read !== undefined) {
79
- if (state.now() < run.read.at) {
80
- return;
81
- }
82
- await readResult(state, run, Math.max(run.read.seq, agent.completionSeq), run.read.attempt + 1);
83
- return;
84
- }
85
- if (agent.completionSeq > run.lastHandledSeq && (agent.status === "idle" || agent.status === "done")) {
86
- await readResult(state, run, agent.completionSeq, 1);
87
- }
88
- }
89
-
90
- // 死亡只认事实:回执,或 pane 消失。
91
- async function missing(state: RunState, run: RunRecord): Promise<void> {
92
- const receipt = state.readExitReceipt(run.sessionFile);
93
- if (receipt !== null) {
94
- await exited(state, run, receipt);
95
- return;
96
- }
97
- if (run.pane === undefined || !(await state.host.hasPane(run.pane.paneId))) {
98
- await exited(state, run, null);
99
- return;
100
- }
101
- run.absentSince ??= state.now();
102
- if (state.now() - run.absentSince >= LOST_CHILD_MS) {
103
- await exited(state, run, null);
104
- }
105
- }
106
-
107
- async function pollRuns(state: RunState): Promise<void> {
108
- let agents: AgentEntry[];
109
- try {
110
- agents = await state.host.listAgents();
111
- } catch {
112
- for (const run of [...state.runs]) {
113
- await recordFailure(state, run);
114
- }
115
- return;
116
- }
117
- for (const run of [...state.runs]) {
118
- if (!run.live) {
119
- continue;
120
- }
121
- try {
122
- await pollRun(state, agents, run);
123
- } catch {
124
- await recordFailure(state, run);
125
- }
126
- }
127
- }
@@ -1,39 +0,0 @@
1
- import { readFileSync, writeFileSync } from "node:fs";
2
-
3
- export interface ExitReceipt {
4
- reason: string;
5
- }
6
-
7
- export type ExitReceiptReader = (sessionFile: string) => ExitReceipt | null;
8
-
9
- export type ExitReceiptWriter = (sessionFile: string, reason: string) => void;
10
-
11
- function receiptFile(sessionFile: string): string {
12
- return `${sessionFile}.exit`;
13
- }
14
-
15
- export const readExitReceipt: ExitReceiptReader = (sessionFile) => {
16
- let raw: string;
17
- try {
18
- raw = readFileSync(receiptFile(sessionFile), "utf8");
19
- } catch (error) {
20
- if ((error as NodeJS.ErrnoException).code === "ENOENT") {
21
- return null;
22
- }
23
- throw error;
24
- }
25
- let parsed: unknown;
26
- try {
27
- parsed = JSON.parse(raw);
28
- } catch {
29
- return null;
30
- }
31
- if (typeof parsed !== "object" || parsed === null || !("reason" in parsed) || typeof parsed.reason !== "string") {
32
- return null;
33
- }
34
- return { reason: parsed.reason };
35
- };
36
-
37
- export const writeExitReceipt: ExitReceiptWriter = (sessionFile, reason) => {
38
- writeFileSync(receiptFile(sessionFile), JSON.stringify({ reason }));
39
- };