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.
package/src/run/start.ts CHANGED
@@ -6,11 +6,12 @@ import { createInbox, enqueue, removeInbox } from "../inbox/index.ts";
6
6
  import { spawnFailed, ToolError } from "./errors.ts";
7
7
  import { paneLabel } from "./naming.ts";
8
8
  import { createPane } from "./pane.ts";
9
- import { wake } from "./poll.ts";
9
+ import { runBaseOf, runsDir } from "./paths.ts";
10
10
  import { resolveProfile, resolveSkills } from "./resolve.ts";
11
11
  import { requireSlot } from "./slot.ts";
12
12
  import { agentArgs, briefText, resolveCwd } from "./spawn-args.ts";
13
13
  import type { RunRecord, RunState } from "./state.ts";
14
+ import { watchRun } from "./watch.ts";
14
15
 
15
16
  const NAME_ATTEMPTS = 100;
16
17
 
@@ -43,10 +44,12 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
43
44
  const runId = randomUUID();
44
45
  const files = (name: string) => {
45
46
  const sessionFile = join(state.sessionsDir, `${name}-${runId}.jsonl`);
47
+ const runBase = runBaseOf(sessionFile);
46
48
  return {
47
49
  sessionFile,
48
- briefFile: `${sessionFile}.brief.md`,
49
- identityFile: `${sessionFile}.identity.md`,
50
+ runBase,
51
+ briefFile: `${runBase}.brief.md`,
52
+ identityFile: `${runBase}.identity.md`,
50
53
  };
51
54
  };
52
55
  const name = state.nextName(profileName);
@@ -58,14 +61,15 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
58
61
  pane: undefined,
59
62
  paneLabel: "",
60
63
  sessionFile: current.sessionFile,
64
+ runBase: current.runBase,
61
65
  cwd,
62
66
  autoExit: profile.autoExit,
63
- lastHandledSeq: 0,
64
- lastDeliveredText: null,
67
+ lastTurn: 0,
65
68
  artifactSeq: 0,
66
- pollFailures: 0,
67
- busy: false,
68
- live: true,
69
+ phase: "running",
70
+ absentChecks: 0,
71
+ paneClosed: false,
72
+ deliveryFailures: 0,
69
73
  };
70
74
  // 先占槽再 await:并发的 run() 必须立刻看到它。
71
75
  state.runs.push(run);
@@ -75,6 +79,7 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
75
79
  run.paneLabel = paneLabel(task) || run.name;
76
80
  run.pane = await createPane(state, run, cwd, run.paneLabel);
77
81
  await mkdir(state.sessionsDir, { recursive: true });
82
+ await mkdir(runsDir(), { recursive: true });
78
83
 
79
84
  for (let retry = 1; ; retry++) {
80
85
  if (state.stopped) {
@@ -84,7 +89,7 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
84
89
  if (profile.systemPrompt !== "task") {
85
90
  await writeFile(current.identityFile, profile.body, "utf8");
86
91
  }
87
- await createInbox(current.sessionFile);
92
+ createInbox(current.runBase);
88
93
  try {
89
94
  await state.host.startAgent({
90
95
  name: run.name,
@@ -93,7 +98,7 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
93
98
  agentArgs: agentArgs(profile, current.identityFile, state.toolName, skillPaths),
94
99
  });
95
100
  // `agent start` 等到 idle 才算就绪,先入队会让第一轮抢跑并把它拖到超时(DEC-0023)。
96
- enqueue(current.sessionFile, `@${current.briefFile}`);
101
+ enqueue(current.runBase, `@${current.briefFile}`);
97
102
  break;
98
103
  } catch (error) {
99
104
  if (!(error instanceof HerdrHostError && error.code === "name_taken")) {
@@ -102,7 +107,7 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
102
107
  await Promise.all([
103
108
  rm(current.briefFile, { force: true }),
104
109
  rm(current.identityFile, { force: true }),
105
- removeInbox(current.sessionFile),
110
+ removeInbox(current.runBase),
106
111
  ]);
107
112
  if (retry >= NAME_ATTEMPTS) {
108
113
  throw new ToolError(
@@ -114,10 +119,11 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
114
119
  await state.host.renameTab({ tabId: run.pane.tabId, label: run.name });
115
120
  current = files(run.name);
116
121
  run.sessionFile = current.sessionFile;
122
+ run.runBase = current.runBase;
117
123
  }
118
124
  }
119
125
 
120
- wake(state);
126
+ watchRun(state, run);
121
127
 
122
128
  return {
123
129
  state: "running",
@@ -130,7 +136,7 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
130
136
  state.release(run);
131
137
  if (state.stopped && pane) {
132
138
  // 清理失败不改变结论:会话已在关闭,run 已被取消。
133
- await state.host.closeTabIfOnlyPane(pane).catch(() => "missing");
139
+ await state.host.closePane(pane.paneId).catch(() => undefined);
134
140
  }
135
141
  if (error instanceof ToolError) {
136
142
  throw error;
package/src/run/state.ts CHANGED
@@ -1,29 +1,26 @@
1
1
  import type { HerdrHost } from "../herdr/index.ts";
2
2
  import type { ProfileCatalog } from "../profile/index.ts";
3
- import type { ExitReceiptReader, SessionReader } from "../session-file/index.ts";
3
+ import type { SessionTailReader } from "../session-file/index.ts";
4
4
  import type { Aggregator } from "./aggregate.ts";
5
5
  import type { ResultHandler, RunResult } from "./result.ts";
6
6
 
7
+ export type RunPhase = "running" | "idle" | "dead" | "closed";
8
+
7
9
  export interface RunServiceDeps {
8
10
  host: HerdrHost;
9
- readLastAssistant: SessionReader;
10
- readExitReceipt: ExitReceiptReader;
11
+ sessionsDir: string;
12
+ readSessionTail: SessionTailReader;
11
13
  loadProfiles: () => ProfileCatalog;
12
14
  trusted: boolean;
13
15
  toolName: string;
14
16
  maxConcurrent: number;
15
17
  maxResultChars: number;
16
18
  aggregateWindowMs: number;
17
- pollIntervalMs: number;
18
- idlePollIntervalMs: number;
19
- onDeliveryError: (error: unknown) => void;
19
+ livenessPollMs: number;
20
+ closeOnFailure: boolean;
21
+ onProblem: (message: string) => void;
20
22
  now?: () => number;
21
- }
22
-
23
- export interface RunRead {
24
- seq: number;
25
- attempt: number;
26
- at: number;
23
+ delay?: (ms: number) => Promise<void>;
27
24
  }
28
25
 
29
26
  export interface RunPane {
@@ -37,32 +34,32 @@ export interface RunRecord {
37
34
  pane: RunPane | undefined;
38
35
  paneLabel: string;
39
36
  sessionFile: string;
37
+ // brief、identity、inbox、turn 事件、结果 artifact 共用的前缀。
38
+ runBase: string;
40
39
  cwd: string;
41
40
  autoExit: boolean;
42
- lastHandledSeq: number;
43
- lastDeliveredText: string | null;
41
+ lastTurn: number;
44
42
  artifactSeq: number;
45
- read?: RunRead;
46
- pollFailures: number;
47
- busy: boolean;
48
- absentSince?: number;
49
- live: boolean;
43
+ phase: RunPhase;
44
+ absentChecks: number;
45
+ paneClosed: boolean;
46
+ deliveryFailures: number;
50
47
  }
51
48
 
52
49
  export interface RunState extends RunServiceDeps {
53
- sessionsDir: string;
54
50
  runs: RunRecord[];
55
51
  pending: Set<Promise<unknown>>;
56
52
  stopped: boolean;
57
53
  resultHandler: ResultHandler | undefined;
58
54
  results: Aggregator<RunResult> | undefined;
59
- pollTimer?: ReturnType<typeof setTimeout>;
60
- pollBusy: boolean;
61
- activeUntil: number;
55
+ scanTimer?: ReturnType<typeof setInterval>;
56
+ livenessTimer?: ReturnType<typeof setInterval>;
57
+ scanning: boolean;
58
+ scanAgain: boolean;
62
59
  now: () => number;
60
+ delay: (ms: number) => Promise<void>;
63
61
  nextName(profile: string): string;
64
62
  active(): string[];
65
63
  available(): string[];
66
- settle(run: RunRecord): void;
67
64
  release(run: RunRecord): void;
68
65
  }
@@ -0,0 +1,95 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { errorText } from "../error/index.ts";
3
+ import { listTurns, readTurn, turnsDir } from "../turn/index.ts";
4
+ import { findAgent } from "./find.ts";
5
+ import { runsDir } from "./paths.ts";
6
+ import { settleLost, settleTurn } from "./settle.ts";
7
+ import type { RunRecord, RunState } from "./state.ts";
8
+
9
+ // 500ms 一次 readdir:没有进程启动,也没有 fs.watch 在 Windows 上的断言崩溃。
10
+ const SCAN_MS = 500;
11
+ const LOST_CHECKS = 3;
12
+
13
+ export function startWatch(state: RunState): void {
14
+ mkdirSync(runsDir(), { recursive: true });
15
+ state.scanTimer = setInterval(() => void scan(state).catch((error) => state.onProblem(errorText(error))), SCAN_MS);
16
+ state.scanTimer.unref?.();
17
+ state.livenessTimer = setInterval(
18
+ () => void checkLiveness(state).catch((error) => state.onProblem(errorText(error))),
19
+ state.livenessPollMs,
20
+ );
21
+ state.livenessTimer.unref?.();
22
+ }
23
+
24
+ export function stopWatch(state: RunState): void {
25
+ if (state.scanTimer !== undefined) {
26
+ clearInterval(state.scanTimer);
27
+ state.scanTimer = undefined;
28
+ }
29
+ if (state.livenessTimer !== undefined) {
30
+ clearInterval(state.livenessTimer);
31
+ state.livenessTimer = undefined;
32
+ }
33
+ }
34
+
35
+ export function watchRun(_state: RunState, run: RunRecord): void {
36
+ mkdirSync(turnsDir(run.runBase), { recursive: true });
37
+ }
38
+
39
+ async function scan(state: RunState): Promise<void> {
40
+ if (state.scanning) {
41
+ state.scanAgain = true;
42
+ return;
43
+ }
44
+ state.scanning = true;
45
+ try {
46
+ for (const run of [...state.runs]) {
47
+ if (run.phase === "closed") {
48
+ continue;
49
+ }
50
+ for (const file of listTurns(run.runBase)) {
51
+ const turn = readTurn(file);
52
+ if (turn === null) {
53
+ continue;
54
+ }
55
+ await settleTurn(state, run, file, turn);
56
+ }
57
+ }
58
+ } finally {
59
+ state.scanning = false;
60
+ if (state.scanAgain) {
61
+ state.scanAgain = false;
62
+ await scan(state);
63
+ }
64
+ }
65
+ }
66
+
67
+ async function checkLiveness(state: RunState): Promise<void> {
68
+ const running = state.runs.filter((run) => run.phase === "running");
69
+ if (running.length === 0) {
70
+ return;
71
+ }
72
+ let agents: Awaited<ReturnType<RunState["host"]["listAgents"]>>;
73
+ try {
74
+ agents = await state.host.listAgents();
75
+ } catch {
76
+ return;
77
+ }
78
+ for (const run of running) {
79
+ if (run.phase !== "running") {
80
+ continue;
81
+ }
82
+ if (findAgent(agents, run)) {
83
+ run.absentChecks = 0;
84
+ continue;
85
+ }
86
+ if (run.pane === undefined || !(await state.host.hasPane(run.pane.paneId))) {
87
+ await settleLost(state, run);
88
+ continue;
89
+ }
90
+ run.absentChecks += 1;
91
+ if (run.absentChecks >= LOST_CHECKS) {
92
+ await settleLost(state, run);
93
+ }
94
+ }
95
+ }
@@ -1,29 +1,27 @@
1
1
  import { readFileSync, statSync } from "node:fs";
2
- import { parseLastAssistant, type SessionSnapshot } from "./jsonl.ts";
2
+ import { parseTail } from "./jsonl.ts";
3
3
  import { readTail, TAIL_WINDOW_BYTES } from "./tail.ts";
4
4
 
5
- export {
6
- type ExitReceipt,
7
- type ExitReceiptReader,
8
- type ExitReceiptWriter,
9
- readExitReceipt,
10
- writeExitReceipt,
11
- } from "./receipt.ts";
5
+ export interface SessionTail {
6
+ pendingToolCall: boolean;
7
+ unreadable: boolean;
8
+ }
12
9
 
13
- export type SessionReader = (path: string) => SessionSnapshot;
10
+ export type SessionTailReader = (path: string) => SessionTail;
14
11
 
15
- const UNREADABLE: SessionSnapshot = { text: null, pendingToolCall: false, empty: false, unreadable: true };
12
+ const UNREADABLE: SessionTail = { pendingToolCall: false, unreadable: true };
16
13
 
17
- export const readLastAssistant: SessionReader = (path) => {
14
+ // 读最后一条 assistant,只为了判断 send 能不能安全续跑。
15
+ export const readSessionTail: SessionTailReader = (path) => {
18
16
  try {
19
17
  const size = statSync(path).size;
20
18
  if (size > TAIL_WINDOW_BYTES) {
21
- const tail = parseLastAssistant(readTail(path, size));
19
+ const tail = parseTail(readTail(path, size));
22
20
  if (!tail.empty) {
23
- return tail;
21
+ return { pendingToolCall: tail.pendingToolCall, unreadable: false };
24
22
  }
25
23
  }
26
- return parseLastAssistant(readFileSync(path, "utf8"));
24
+ return { pendingToolCall: parseTail(readFileSync(path, "utf8")).pendingToolCall, unreadable: false };
27
25
  } catch {
28
26
  return { ...UNREADABLE };
29
27
  }
@@ -1,8 +1,6 @@
1
- export interface SessionSnapshot {
2
- text: string | null;
1
+ export interface TailSnapshot {
3
2
  pendingToolCall: boolean;
4
3
  empty: boolean;
5
- unreadable: boolean;
6
4
  }
7
5
 
8
6
  interface SessionEntry {
@@ -13,14 +11,6 @@ interface SessionEntry {
13
11
  };
14
12
  }
15
13
 
16
- function isTextBlock(block: unknown): block is { type: "text"; text: string } {
17
- if (typeof block !== "object" || block === null) {
18
- return false;
19
- }
20
- const candidate = block as { type?: unknown; text?: unknown };
21
- return candidate.type === "text" && typeof candidate.text === "string";
22
- }
23
-
24
14
  function hasToolCall(content: unknown): boolean {
25
15
  if (!Array.isArray(content)) {
26
16
  return false;
@@ -34,23 +24,10 @@ function hasToolCall(content: unknown): boolean {
34
24
  });
35
25
  }
36
26
 
37
- function textOf(entry: SessionEntry): string | null {
38
- const content = entry.message?.content;
39
- if (!Array.isArray(content)) {
40
- return null;
41
- }
42
- const text = content
43
- .filter(isTextBlock)
44
- .map((block) => block.text)
45
- .filter((block) => block.trim() !== "")
46
- .join("\n")
47
- .trim();
48
- return text === "" ? null : text;
49
- }
50
-
51
- export function parseLastAssistant(raw: string): SessionSnapshot {
27
+ // 只回答 send 续跑前的一个问题:最后一条 assistant 是不是停在工具调用上。
28
+ export function parseTail(raw: string): TailSnapshot {
52
29
  const lines = raw.split("\n");
53
- for (let index = lines.length - 1; index >= 0; index--) {
30
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
54
31
  const line = lines[index]?.trim();
55
32
  if (!line) {
56
33
  continue;
@@ -68,12 +45,7 @@ export function parseLastAssistant(raw: string): SessionSnapshot {
68
45
  if (entry.type !== "message" || entry.message?.role !== "assistant") {
69
46
  continue;
70
47
  }
71
- return {
72
- text: textOf(entry),
73
- pendingToolCall: hasToolCall(entry.message?.content),
74
- empty: false,
75
- unreadable: false,
76
- };
48
+ return { pendingToolCall: hasToolCall(entry.message.content), empty: false };
77
49
  }
78
- return { text: null, pendingToolCall: false, empty: true, unreadable: false };
50
+ return { pendingToolCall: false, empty: true };
79
51
  }
package/src/tool/index.ts CHANGED
@@ -14,17 +14,10 @@ interface ToolDeps {
14
14
  service: () => RunService;
15
15
  }
16
16
 
17
- function started(result: RunStarted) {
17
+ // content 进模型上下文,只放模型能用的字段。details 只给 UI 和 session 条目。
18
+ function envelope(result: RunStarted | SendResult) {
18
19
  return {
19
- content: [{ type: "text" as const, text: JSON.stringify(result) }],
20
- details: result,
21
- isError: false,
22
- };
23
- }
24
-
25
- function sent(result: SendResult) {
26
- return {
27
- content: [{ type: "text" as const, text: JSON.stringify(result) }],
20
+ content: [{ type: "text" as const, text: JSON.stringify({ state: result.state, name: result.name }) }],
28
21
  details: result,
29
22
  isError: false,
30
23
  };
@@ -42,9 +35,9 @@ export function createTool({ config, profiles, service }: ToolDeps) {
42
35
  }
43
36
  try {
44
37
  if (params.action === "run") {
45
- return started(await service().run(params.profile, params.task, params.cwd));
38
+ return envelope(await service().run(params.profile, params.task, params.cwd));
46
39
  }
47
- return sent(await service().send(params.name, params.message));
40
+ return envelope(await service().send(params.name, params.message));
48
41
  } catch (error) {
49
42
  if (error instanceof ToolError) {
50
43
  return toolFailed(error);
@@ -1,4 +1,4 @@
1
- import type { RunResult, UnknownReason } from "../run/index.ts";
1
+ import type { RunResult } from "../run/index.ts";
2
2
 
3
3
  export interface ResultMessage {
4
4
  customType: string;
@@ -10,21 +10,24 @@ interface MessageSink {
10
10
  sendMessage(message: ResultMessage, options?: { triggerTurn?: boolean }): void;
11
11
  }
12
12
 
13
- const UNKNOWN_TEXT: Record<UnknownReason, string> = {
14
- poll_failed: "status could not be read",
15
- no_result: "no result was read",
16
- close_failed: "result delivered, but the tab did not close",
17
- quitted: "the child exited without a result",
18
- pane_exited: "the pane exited without a result",
13
+ const LABEL: Record<RunResult["state"], string> = {
14
+ done: "done",
15
+ error: "failed",
16
+ aborted: "interrupted",
17
+ quit: "stopped before reporting a result",
18
+ lost: "lost contact; no result",
19
19
  };
20
20
 
21
21
  function resultText(result: RunResult): string {
22
- if (result.state === "unknown") {
23
- return `[subagent ${result.name}] ${UNKNOWN_TEXT[result.reason]}\n\nSession file: ${result.sessionFile}`;
24
- }
22
+ const tag = `[subagent ${result.name}]`;
25
23
  const artifact = result.artifact ? `\n\nFull result: ${result.artifact}` : "";
26
24
  const warning = result.warning ? `\n\n${result.warning}` : "";
27
- return `[subagent ${result.name}] done\n\n${result.text}${artifact}${warning}`;
25
+ if (result.state === "done") {
26
+ return `${tag} done\n\n${result.text ?? ""}${artifact}${warning}`;
27
+ }
28
+ const reason = result.errorMessage === undefined ? "" : `\n\n${result.errorMessage}`;
29
+ const partial = result.text === undefined ? "" : `\n\nPartial answer (not a completed result):\n${result.text}`;
30
+ return `${tag} ${LABEL[result.state]}${reason}${partial}${artifact}${warning}`;
28
31
  }
29
32
 
30
33
  export function sendResults(sink: MessageSink, results: RunResult[]): void {