pi-herdr-subagents-lite 0.7.1 → 0.8.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 CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  本文件记录已发布版本的用户可见变更。更细的过程见 git log。破坏性变更标 **BREAKING**。0.5.2 及更早的变更见旧仓 `setwhite/pi-herdr-subagents-lite` 的 tag `v0.3.0`–`v0.5.2`。
4
4
 
5
+ ## 0.8.0 — 2026-11-03
6
+
7
+ - 模型不再看到子 session 路径与 pane id:`run` 与 `send` 的工具返回只剩 `state` 与 `name`,`paneId` 与 `sessionFile` 留在 `details`。`unknown` 结果消息不再附 `Session file:`。`send` 的错误只报子代理名。目的是不让父代理顺着路径去读子会话正文。
8
+ - **BREAKING**:文件位置改了。子 session 落在父会话桶的 `runs/` 子目录,brief、identity、inbox、exit 回执、结果 artifact 落在 `<agent-dir>/pi-herdr-subagents-lite/runs/` 一层平铺,共用 `<name>-<runId>` 前缀。超长结果的 `Full result:` 指向新位置。路径只影响新 run。
9
+ - 修:子代理收工、会话关掉后 tab 留在原地。关闭改用 `pane close`,不再先核对 tab 里只有一个 pane —— 那个核对撞上 herdr 重登记 pane 的窗口就会静默放弃。同 tab 里人开的 pane 不受影响。
10
+ - 关 pane 失败不再是终态:补一条 `close_failed`,子代理死亡时再关一次。
11
+ - 修:新回合写出和上一轮逐字相同的答案时,结果被当成重复丢掉,也不关 tab。判据改成「session 文件尾部换过没有」。
12
+
13
+ ## 0.7.2 — 2026-11-03
14
+
15
+ - 内置工具文案改为讲用法:`description` 说何时用 `run`、何时用 `send`。
16
+ - 删掉 guideline 里 "The parent handles user interaction, cross-task synthesis, and decisions; subagents execute." 一行。剩下三条讲 `run` 与 `send` 的语义,最后一条列 profile。
17
+
5
18
  ## 0.7.1 — 2026-11-03
6
19
 
7
20
  - 发布:`CHANGELOG.md` 进 `files`。此前 tarball 里没有它,pi 更新扩展后看不到变更。本版起补上。首次更新到本版时,"Extension Updates" 下只有这一条。
package/README.md CHANGED
@@ -71,12 +71,11 @@ The block below lists every key. Each value is the default.
71
71
  // Tool text overrides. Each key defaults to unset, which keeps the built-in text shown below.
72
72
  "prompts": {
73
73
  // Replaces the built-in description.
74
- "description": "Run subagents and send them messages.",
74
+ "description": "Use run when a task is self-contained and long-running. Use send to pass information to a subagent.",
75
75
  // The one-line entry in Available tools. Empty = keep the tool out of that list.
76
76
  "snippet": "",
77
77
  // Replaces the built-in guideline lines. Keep {{profiles}} to list the profiles.
78
78
  "guidelines": [
79
- "The parent handles user interaction, cross-task synthesis, and decisions; subagents execute.",
80
79
  "run only starts; it does not wait. The result arrives later as a message.",
81
80
  "send only delivers; no state tracking.",
82
81
  "Available profiles:\n{{profiles}}"
package/README.zh-CN.md CHANGED
@@ -71,12 +71,11 @@ pi -e /path/to/pi-herdr-subagents-lite/src/index.ts # 只对当前进程生效
71
71
  // 工具文案覆盖。每个键默认未设置,用下面这份内置文案。
72
72
  "prompts": {
73
73
  // 替换内置描述。
74
- "description": "Run subagents and send them messages.",
74
+ "description": "Use run when a task is self-contained and long-running. Use send to pass information to a subagent.",
75
75
  // Available tools 里的那一行。空 = 不出现在该列表。
76
76
  "snippet": "",
77
77
  // 替换内置 guideline 各行。保留 {{profiles}} 才会列出 profile。
78
78
  "guidelines": [
79
- "The parent handles user interaction, cross-task synthesis, and decisions; subagents execute.",
80
79
  "run only starts; it does not wait. The result arrives later as a message.",
81
80
  "send only delivers; no state tracking.",
82
81
  "Available profiles:\n{{profiles}}"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-herdr-subagents-lite",
3
- "version": "0.7.1",
3
+ "version": "0.8.0",
4
4
  "description": "Run pi subagents in herdr panes.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,5 +1,5 @@
1
1
  import { inboxCount } from "../inbox/index.ts";
2
- import { AUTO_EXIT_ENV } from "../run/index.ts";
2
+ import { AUTO_EXIT_ENV, runBaseOf } from "../run/index.ts";
3
3
  import type { ExtensionRegistrar } from "./index.ts";
4
4
 
5
5
  export function watchAutoExit(pi: ExtensionRegistrar): { reset(): void } {
@@ -19,7 +19,7 @@ export function watchAutoExit(pi: ExtensionRegistrar): { reset(): void } {
19
19
  return;
20
20
  }
21
21
  const sessionFile = ctx.sessionManager.getSessionFile();
22
- if (!sessionFile || inboxCount(sessionFile) > 0) {
22
+ if (!sessionFile || inboxCount(runBaseOf(sessionFile)) > 0) {
23
23
  return;
24
24
  }
25
25
  exiting = true;
@@ -5,7 +5,7 @@ import { errorText } from "../error/index.ts";
5
5
  import type { HerdrHost } from "../herdr/index.ts";
6
6
  import { drain, hasInbox, pumpInbox } from "../inbox/index.ts";
7
7
  import type { ProfileCatalog, ProfileSources } from "../profile/index.ts";
8
- import { createRunService, type RunService } from "../run/index.ts";
8
+ import { childSessionsDir, createRunService, type RunService, runBaseOf } from "../run/index.ts";
9
9
  import type { ExitReceiptReader, ExitReceiptWriter, SessionReader } from "../session-file/index.ts";
10
10
  import { createTool, type ResultMessage, type SubagentTool, sendResults } from "../tool/index.ts";
11
11
  import { watchAutoExit } from "./auto-exit.ts";
@@ -76,7 +76,11 @@ export function createExtension(deps: ExtensionDeps): (pi: ExtensionRegistrar) =
76
76
 
77
77
  const startInbox = (ctx: SessionContext) => {
78
78
  const sessionFile = ctx.sessionManager.getSessionFile();
79
- if (!sessionFile || !hasInbox(sessionFile)) {
79
+ if (sessionFile === undefined) {
80
+ return;
81
+ }
82
+ const base = runBaseOf(sessionFile);
83
+ if (!hasInbox(base)) {
80
84
  return;
81
85
  }
82
86
  inboxFailures = 0;
@@ -85,7 +89,7 @@ export function createExtension(deps: ExtensionDeps): (pi: ExtensionRegistrar) =
85
89
  };
86
90
  stopPump = pumpInbox({
87
91
  pollMs: config.inboxPollMs,
88
- tick: () => drain(sessionFile, deliver),
92
+ tick: () => drain(base, deliver),
89
93
  onCycle(error) {
90
94
  if (error === undefined) {
91
95
  inboxFailures = 0;
@@ -106,6 +110,7 @@ export function createExtension(deps: ExtensionDeps): (pi: ExtensionRegistrar) =
106
110
  service?.shutdown();
107
111
  service = createRunService({
108
112
  host,
113
+ sessionsDir: childSessionsDir(ctx.sessionManager.getSessionFile()),
109
114
  readLastAssistant: deps.readLastAssistant,
110
115
  readExitReceipt: deps.readExitReceipt,
111
116
  loadProfiles: () => deps.loadProfiles(sources),
@@ -1,6 +1,6 @@
1
1
  import type { Config, ShutdownReason } from "../config/index.ts";
2
2
  import { hasInbox } from "../inbox/index.ts";
3
- import type { RunService } from "../run/index.ts";
3
+ import { type RunService, runBaseOf } from "../run/index.ts";
4
4
  import type { ExitReceiptWriter } from "../session-file/index.ts";
5
5
  import type { ExtensionRegistrar, SessionContext } from "./index.ts";
6
6
 
@@ -21,14 +21,12 @@ export function watchShutdown(pi: ExtensionRegistrar, deps: ShutdownDeps): void
21
21
  deps.stopInbox();
22
22
  const closing = deps.takeService();
23
23
  const sessionFile = ctx.sessionManager.getSessionFile();
24
- if (sessionFile && hasInbox(sessionFile)) {
25
- deps.writeExitReceipt(sessionFile, event.reason);
24
+ const base = sessionFile === undefined ? undefined : runBaseOf(sessionFile);
25
+ if (base !== undefined && hasInbox(base)) {
26
+ deps.writeExitReceipt(base, event.reason);
26
27
  }
27
28
  if (closing && deps.config.closeChildrenOn.includes(event.reason)) {
28
- const { kept, failed } = await closing.closeChildren();
29
- for (const name of kept) {
30
- ctx.ui.notify(`child "${name}" kept running: its tab has more than one pane`, "warning");
31
- }
29
+ const { failed } = await closing.closeChildren();
32
30
  for (const failure of failed) {
33
31
  ctx.ui.notify(`could not close child "${failure.name}": ${failure.reason}`, "error");
34
32
  }
@@ -2,8 +2,6 @@ import type { AgentEntry, AgentSnapshot, StartAgentInput } from "./agent.ts";
2
2
  import { createAgentCommands } from "./agent.ts";
3
3
  import { createHerdrExec, HerdrHostError } from "./cli.ts";
4
4
  import type {
5
- CloseTabInput,
6
- CloseTabResult,
7
5
  CreatedTab,
8
6
  CreatedWorkspace,
9
7
  CreateTabInput,
@@ -23,10 +21,10 @@ export interface HerdrHost {
23
21
  startAgent(input: StartAgentInput): Promise<void>;
24
22
  hasPane(paneId: string): Promise<boolean>;
25
23
  listAgents(): Promise<AgentEntry[]>;
26
- closeTabIfOnlyPane(input: CloseTabInput): Promise<CloseTabResult>;
24
+ closePane(paneId: string): Promise<void>;
27
25
  }
28
26
 
29
- export type { AgentEntry, AgentSnapshot, CloseTabResult, StartAgentInput };
27
+ export type { AgentEntry, AgentSnapshot, StartAgentInput };
30
28
 
31
29
  export function createHerdrHost(bin: string): HerdrHost {
32
30
  const { execJson } = createHerdrExec(bin);
package/src/herdr/pane.ts CHANGED
@@ -25,13 +25,6 @@ function envArgs(env: Record<string, string>): string[] {
25
25
  return Object.entries(env).flatMap(([key, value]) => ["--env", `${key}=${value}`]);
26
26
  }
27
27
 
28
- export interface CloseTabInput {
29
- tabId: string;
30
- paneId: string;
31
- }
32
-
33
- export type CloseTabResult = "closed" | "kept" | "missing";
34
-
35
28
  export interface RenameTabInput {
36
29
  tabId: string;
37
30
  label: string;
@@ -48,13 +41,10 @@ interface WorkspaceInfo {
48
41
 
49
42
  interface TabInfo {
50
43
  tab_id: string;
51
- workspace_id: string;
52
- pane_count: number;
53
44
  }
54
45
 
55
46
  interface PaneInfo {
56
47
  pane_id: string;
57
- tab_id: string;
58
48
  }
59
49
 
60
50
  export function createPaneCommands(exec: ExecHerdr) {
@@ -104,24 +94,14 @@ export function createPaneCommands(exec: ExecHerdr) {
104
94
  return result.panes.some((pane) => pane.pane_id === paneId);
105
95
  },
106
96
 
107
- async closeTabIfOnlyPane({ tabId, paneId }: CloseTabInput): Promise<CloseTabResult> {
97
+ // 只关自己记下的 pane,不看 tab 里还有什么。pane 已经不在了也算关掉。
98
+ async closePane(paneId: string): Promise<void> {
108
99
  try {
109
- const { tab } = await exec<{ tab: TabInfo }>(["tab", "get", tabId]);
110
- if (tab.pane_count !== 1) {
111
- return "kept";
112
- }
113
- const panes = await exec<{ panes: PaneInfo[] }>(["pane", "list", "--workspace", tab.workspace_id]);
114
- const tabPanes = panes.panes.filter((pane) => pane.tab_id === tabId);
115
- if (tabPanes.length !== 1 || tabPanes[0]?.pane_id !== paneId) {
116
- return "kept";
117
- }
118
- await exec(["tab", "close", tabId]);
119
- return "closed";
100
+ await exec(["pane", "close", paneId]);
120
101
  } catch (error) {
121
- if (error instanceof HerdrHostError && error.code === "tab_not_found") {
122
- return "missing";
102
+ if (!(error instanceof HerdrHostError && error.code === "pane_not_found")) {
103
+ throw error;
123
104
  }
124
- throw error;
125
105
  }
126
106
  },
127
107
  };
@@ -4,13 +4,13 @@ import { join } from "node:path";
4
4
 
5
5
  const MESSAGE_SUFFIX = ".md";
6
6
 
7
- function inboxDir(sessionFile: string): string {
8
- return `${sessionFile}.inbox`;
7
+ function inboxDir(base: string): string {
8
+ return `${base}.inbox`;
9
9
  }
10
10
 
11
- export function hasInbox(sessionFile: string): boolean {
11
+ export function hasInbox(base: string): boolean {
12
12
  try {
13
- return statSync(inboxDir(sessionFile)).isDirectory();
13
+ return statSync(inboxDir(base)).isDirectory();
14
14
  } catch (error) {
15
15
  if ((error as NodeJS.ErrnoException).code === "ENOENT") {
16
16
  return false;
@@ -19,12 +19,12 @@ export function hasInbox(sessionFile: string): boolean {
19
19
  }
20
20
  }
21
21
 
22
- export function createInbox(sessionFile: string): void {
23
- mkdirSync(inboxDir(sessionFile), { recursive: true });
22
+ export function createInbox(base: string): void {
23
+ mkdirSync(inboxDir(base), { recursive: true });
24
24
  }
25
25
 
26
- export function removeInbox(sessionFile: string): void {
27
- rmSync(inboxDir(sessionFile), { recursive: true, force: true });
26
+ export function removeInbox(base: string): void {
27
+ rmSync(inboxDir(base), { recursive: true, force: true });
28
28
  }
29
29
 
30
30
  function pendingNames(dir: string): string[] {
@@ -40,12 +40,12 @@ function pendingNames(dir: string): string[] {
40
40
  }
41
41
  }
42
42
 
43
- export function inboxCount(sessionFile: string): number {
44
- return pendingNames(inboxDir(sessionFile)).length;
43
+ export function inboxCount(base: string): number {
44
+ return pendingNames(inboxDir(base)).length;
45
45
  }
46
46
 
47
- export function enqueue(sessionFile: string, text: string): void {
48
- const dir = inboxDir(sessionFile);
47
+ export function enqueue(base: string, text: string): void {
48
+ const dir = inboxDir(base);
49
49
  mkdirSync(dir, { recursive: true });
50
50
  const name = `${String(process.hrtime.bigint()).padStart(20, "0")}-${randomUUID()}${MESSAGE_SUFFIX}`;
51
51
  const temp = join(dir, `.${randomUUID()}.tmp`);
@@ -53,8 +53,8 @@ export function enqueue(sessionFile: string, text: string): void {
53
53
  renameSync(temp, join(dir, name));
54
54
  }
55
55
 
56
- export function drain(sessionFile: string, deliver: (text: string) => void): number {
57
- const dir = inboxDir(sessionFile);
56
+ export function drain(base: string, deliver: (text: string) => void): number {
57
+ const dir = inboxDir(base);
58
58
  let delivered = 0;
59
59
  for (const name of pendingNames(dir)) {
60
60
  const path = join(dir, name);
@@ -1,11 +1,11 @@
1
1
  import { rename, rm, writeFile } from "node:fs/promises";
2
2
 
3
- function artifactPath(sessionFile: string, seq: number): string {
4
- return `${sessionFile}.result-${seq}.md`;
3
+ function artifactPath(base: string, seq: number): string {
4
+ return `${base}.result-${seq}.md`;
5
5
  }
6
6
 
7
- export async function writeArtifact(sessionFile: string, seq: number, text: string): Promise<string> {
8
- const path = artifactPath(sessionFile, seq);
7
+ export async function writeArtifact(base: string, seq: number, text: string): Promise<string> {
8
+ const path = artifactPath(base, seq);
9
9
  const temp = `${path}.tmp`;
10
10
  try {
11
11
  await writeFile(temp, text);
package/src/run/close.ts CHANGED
@@ -1,43 +1,43 @@
1
1
  import { errorText } from "../error/index.ts";
2
2
  import type { RunResult } from "./result.ts";
3
- import type { RunPane, RunRecord, RunState } from "./state.ts";
3
+ import type { RunRecord, RunState } from "./state.ts";
4
4
 
5
5
  export function shouldClose(run: RunRecord, result: RunResult): boolean {
6
6
  return result.state === "done" && run.autoExit;
7
7
  }
8
8
 
9
- export async function closeTab(state: RunState, run: RunRecord): Promise<void> {
10
- if (!run.pane) {
9
+ // 只关自己记下的 pane,所以不需要先确认 tab 里有什么。pane 已经不在了也算关掉。
10
+ export async function closeRunPane(state: RunState, run: RunRecord): Promise<void> {
11
+ const pane = run.pane;
12
+ if (pane === undefined) {
11
13
  return;
12
14
  }
13
- await state.host.closeTabIfOnlyPane(run.pane);
15
+ await state.host.closePane(pane.paneId);
16
+ run.paneClosed = true;
14
17
  }
15
18
 
16
19
  export interface CloseChildrenResult {
17
- kept: string[];
18
20
  failed: Array<{ name: string; reason: string }>;
19
21
  }
20
22
 
21
23
  interface CloseOutcome {
22
24
  name: string;
23
- kept: boolean;
24
25
  failure?: string;
25
26
  }
26
27
 
27
- async function closePane(state: RunState, run: RunRecord, pane: RunPane): Promise<CloseOutcome> {
28
- try {
29
- const outcome = await state.host.closeTabIfOnlyPane(pane);
30
- return { name: run.name, kept: outcome === "kept" };
31
- } catch (error) {
32
- return { name: run.name, kept: false, failure: errorText(error) };
33
- }
34
- }
35
-
36
28
  export async function closeRuns(state: RunState, runs: RunRecord[]): Promise<CloseChildrenResult> {
37
- const targets = runs.filter((run): run is RunRecord & { pane: RunPane } => run.pane !== undefined);
38
- const outcomes = await Promise.all(targets.map((run) => closePane(state, run, run.pane)));
29
+ const targets = runs.filter((run) => run.pane !== undefined);
30
+ const outcomes: CloseOutcome[] = await Promise.all(
31
+ targets.map(async (run) => {
32
+ try {
33
+ await closeRunPane(state, run);
34
+ return { name: run.name };
35
+ } catch (error) {
36
+ return { name: run.name, failure: errorText(error) };
37
+ }
38
+ }),
39
+ );
39
40
  return {
40
- kept: outcomes.filter((outcome) => outcome.kept).map((outcome) => outcome.name),
41
41
  failed: outcomes.flatMap((outcome) =>
42
42
  outcome.failure === undefined ? [] : [{ name: outcome.name, reason: outcome.failure }],
43
43
  ),
package/src/run/index.ts CHANGED
@@ -1,6 +1,3 @@
1
- import { join } from "node:path";
2
- import { dataDir } from "../config/index.ts";
3
- import { agentDir } from "../profile/index.ts";
4
1
  import { createAggregator } from "./aggregate.ts";
5
2
  import { type CloseChildrenResult, closeRuns } from "./close.ts";
6
3
  import { createNamer } from "./naming.ts";
@@ -36,7 +33,6 @@ function takeRuns(state: RunState): RunRecord[] {
36
33
  export function createRunService(deps: RunServiceDeps): RunService {
37
34
  const state: RunState = {
38
35
  ...deps,
39
- sessionsDir: join(dataDir(agentDir()), "sessions"),
40
36
  runs: [],
41
37
  pending: new Set(),
42
38
  stopped: false,
@@ -95,6 +91,7 @@ export function createRunService(deps: RunServiceDeps): RunService {
95
91
 
96
92
  export type { CloseChildrenResult } from "./close.ts";
97
93
  export { ToolError } from "./errors.ts";
94
+ export { childSessionsDir, runBaseOf, runsDir } from "./paths.ts";
98
95
  export { profileLabel } from "./resolve.ts";
99
96
  export type { ResultHandler, RunResult, UnknownReason } from "./result.ts";
100
97
  export type { SendResult } from "./send.ts";
package/src/run/paths.ts CHANGED
@@ -1,5 +1,22 @@
1
- import { relative } from "node:path";
1
+ import { basename, dirname, join, relative } from "node:path";
2
+ import { dataDir } from "../config/index.ts";
3
+ import { agentDir } from "../profile/index.ts";
2
4
 
3
5
  export function samePath(left: string, right: string): boolean {
4
6
  return relative(left, right) === "";
5
7
  }
8
+
9
+ export function runsDir(): string {
10
+ return join(dataDir(agentDir()), "runs");
11
+ }
12
+
13
+ // run 的附属文件共用一个前缀:brief、identity、inbox、exit 回执、结果 artifact。
14
+ export function runBaseOf(sessionFile: string): string {
15
+ return join(runsDir(), basename(sessionFile, ".jsonl"));
16
+ }
17
+
18
+ // 子会话进父会话所在的桶,与父会话同为 sessions 下的目录。
19
+ export function childSessionsDir(parentSessionFile: string | undefined): string {
20
+ const sessionsDir = parentSessionFile === undefined ? join(agentDir(), "sessions") : dirname(parentSessionFile);
21
+ return join(sessionsDir, "runs");
22
+ }
@@ -1,5 +1,5 @@
1
1
  import type { ExitReceipt } from "../session-file/index.ts";
2
- import { closeTab, shouldClose } from "./close.ts";
2
+ import { closeRunPane, shouldClose } from "./close.ts";
3
3
  import type { RunResult } from "./result.ts";
4
4
  import { doneResult, unknownResult } from "./result.ts";
5
5
  import type { RunRecord, RunState } from "./state.ts";
@@ -18,6 +18,16 @@ export async function recordFailure(state: RunState, run: RunRecord): Promise<vo
18
18
  }
19
19
  }
20
20
 
21
+ // 文本相同也要看字节数:另一个回合可能写出逐字相同的答案。
22
+ function newTail(run: RunRecord, text: string, size: number): boolean {
23
+ return text !== run.lastDeliveredText || size !== run.lastDeliveredSize;
24
+ }
25
+
26
+ function markDelivered(run: RunRecord, text: string, size: number): void {
27
+ run.lastDeliveredText = text;
28
+ run.lastDeliveredSize = size;
29
+ }
30
+
21
31
  export async function readResult(state: RunState, run: RunRecord, seq: number, attempt: number): Promise<void> {
22
32
  run.read = undefined;
23
33
  if (!run.live) {
@@ -30,10 +40,10 @@ export async function readResult(state: RunState, run: RunRecord, seq: number, a
30
40
  }
31
41
  if (snapshot.text !== null) {
32
42
  run.lastHandledSeq = seq;
33
- if (snapshot.text === run.lastDeliveredText) {
43
+ if (!newTail(run, snapshot.text, snapshot.size)) {
34
44
  return;
35
45
  }
36
- run.lastDeliveredText = snapshot.text;
46
+ markDelivered(run, snapshot.text, snapshot.size);
37
47
  await finish(state, run, await doneResult(run, snapshot.text, state.maxResultChars));
38
48
  return;
39
49
  }
@@ -56,24 +66,40 @@ export async function exited(state: RunState, run: RunRecord, receipt: ExitRecei
56
66
  const tail = state.readLastAssistant(run.sessionFile);
57
67
  const text = tail.pendingToolCall ? null : tail.text;
58
68
  if (text !== null) {
59
- if (text !== run.lastDeliveredText) {
60
- run.lastDeliveredText = text;
69
+ if (newTail(run, text, tail.size)) {
70
+ markDelivered(run, text, tail.size);
61
71
  await finish(state, run, await doneResult(run, text, state.maxResultChars));
72
+ return;
62
73
  }
63
74
  } else if (run.lastDeliveredText === null) {
64
- const reason = receipt === null ? "pane_exited" : "quitted";
65
- await finish(state, run, unknownResult(run, reason));
75
+ await finish(state, run, unknownResult(run, receipt === null ? "pane_exited" : "quitted"));
76
+ return;
66
77
  }
78
+ await closeAfterExit(state, run);
67
79
  state.settle(run);
68
80
  }
69
81
 
82
+ // 投递过结果不代表 pane 关掉了:子代理死亡是最后一次补关机会。
83
+ async function closeAfterExit(state: RunState, run: RunRecord): Promise<void> {
84
+ if (!run.autoExit || run.pane === undefined || run.paneClosed) {
85
+ return;
86
+ }
87
+ try {
88
+ await closeRunPane(state, run);
89
+ } catch {
90
+ await state.results?.push(unknownResult(run, "close_failed"));
91
+ }
92
+ }
93
+
70
94
  async function finish(state: RunState, run: RunRecord, result: RunResult): Promise<void> {
71
95
  await state.results?.push(result);
72
96
  if (shouldClose(run, result)) {
73
97
  try {
74
- await closeTab(state, run);
98
+ await closeRunPane(state, run);
75
99
  } catch {
100
+ // 关不掉不算结算:保留 live,子代理死亡时再试一次(DEC-0060)。
76
101
  await state.results?.push(unknownResult(run, "close_failed"));
102
+ return;
77
103
  }
78
104
  state.settle(run);
79
105
  return;
package/src/run/poll.ts CHANGED
@@ -89,7 +89,7 @@ async function pollRun(state: RunState, agents: AgentEntry[], run: RunRecord): P
89
89
 
90
90
  // 死亡只认事实:回执,或 pane 消失。
91
91
  async function missing(state: RunState, run: RunRecord): Promise<void> {
92
- const receipt = state.readExitReceipt(run.sessionFile);
92
+ const receipt = state.readExitReceipt(run.runBase);
93
93
  if (receipt !== null) {
94
94
  await exited(state, run, receipt);
95
95
  return;
package/src/run/result.ts CHANGED
@@ -9,7 +9,6 @@ export interface DoneResult {
9
9
  text: string;
10
10
  artifact?: string;
11
11
  warning?: string;
12
- sessionFile: string;
13
12
  }
14
13
 
15
14
  export type UnknownReason = "poll_failed" | "no_result" | "close_failed" | "quitted" | "pane_exited";
@@ -18,7 +17,6 @@ export interface UnknownResult {
18
17
  state: "unknown";
19
18
  name: string;
20
19
  reason: UnknownReason;
21
- sessionFile: string;
22
20
  }
23
21
 
24
22
  export type RunResult = DoneResult | UnknownResult;
@@ -26,14 +24,14 @@ export type RunResult = DoneResult | UnknownResult;
26
24
  export type ResultHandler = (results: RunResult[]) => void | Promise<void>;
27
25
 
28
26
  export async function doneResult(run: RunRecord, text: string, limit: number): Promise<DoneResult> {
29
- const base = { state: "done" as const, name: run.name, sessionFile: run.sessionFile };
27
+ const base = { state: "done" as const, name: run.name };
30
28
  if (text.length <= limit) {
31
29
  return { ...base, text };
32
30
  }
33
31
  const head = leadingChars(text, limit);
34
32
  const seq = run.artifactSeq + 1;
35
33
  try {
36
- const artifact = await writeArtifact(run.sessionFile, seq, text);
34
+ const artifact = await writeArtifact(run.runBase, seq, text);
37
35
  run.artifactSeq = seq;
38
36
  return { ...base, text: head, artifact };
39
37
  } catch (error) {
@@ -46,6 +44,5 @@ export function unknownResult(run: RunRecord, reason: UnknownReason): UnknownRes
46
44
  state: "unknown",
47
45
  name: run.name,
48
46
  reason,
49
- sessionFile: run.sessionFile,
50
47
  };
51
48
  }
package/src/run/send.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { writeFile } from "node:fs/promises";
3
3
  import { createInbox, enqueue } from "../inbox/index.ts";
4
- import { closeTab } from "./close.ts";
4
+ import { closeRunPane } from "./close.ts";
5
5
  import { spawnFailed, ToolError } from "./errors.ts";
6
6
  import { findAgent } from "./find.ts";
7
7
  import { createPane } from "./pane.ts";
@@ -48,16 +48,16 @@ export async function send(state: RunState, name: string, message: string): Prom
48
48
  run.pollFailures = 0;
49
49
  }
50
50
  wake(state);
51
- await enqueue(run.sessionFile, inboxMessage(message));
51
+ await enqueue(run.runBase, inboxMessage(message));
52
52
  return { state: "sent", name };
53
53
  }
54
54
 
55
55
  if (!existsSync(run.sessionFile)) {
56
- throw new ToolError("session_missing", `child session "${run.sessionFile}" is missing; start a new run`);
56
+ throw new ToolError("session_missing", `"${name}" has no child session to resume; start a new run`);
57
57
  }
58
58
  const tail = state.readLastAssistant(run.sessionFile);
59
59
  if (tail.unreadable) {
60
- throw new ToolError("session_unreadable", `child session "${run.sessionFile}" cannot be read; start a new run`);
60
+ throw new ToolError("session_unreadable", `"${name}" has a child session that cannot be read; start a new run`);
61
61
  }
62
62
  if (tail.pendingToolCall) {
63
63
  throw new ToolError(
@@ -70,7 +70,7 @@ export async function send(state: RunState, name: string, message: string): Prom
70
70
  requireSlot(state);
71
71
  const cwd = run.cwd;
72
72
  const skillPaths = await resolveSkills(profile, cwd, state.trusted);
73
- const identityFile = `${run.sessionFile}.identity.md`;
73
+ const identityFile = `${run.runBase}.identity.md`;
74
74
  const previousPaneId = run.pane?.paneId;
75
75
  const envChanged = run.autoExit !== profile.autoExit;
76
76
  run.autoExit = profile.autoExit;
@@ -81,7 +81,7 @@ export async function send(state: RunState, name: string, message: string): Prom
81
81
  run.pane = undefined;
82
82
  } else if (envChanged) {
83
83
  try {
84
- await closeTab(state, run);
84
+ await closeRunPane(state, run);
85
85
  } catch (error) {
86
86
  throw spawnFailed(error, previousPaneId, false);
87
87
  }
@@ -93,10 +93,11 @@ export async function send(state: RunState, name: string, message: string): Prom
93
93
  try {
94
94
  const pane = run.pane ?? (await createPane(state, run, cwd, run.paneLabel || run.name));
95
95
  run.pane = pane;
96
+ run.paneClosed = false;
96
97
  if (profile.systemPrompt !== "task") {
97
98
  await writeFile(identityFile, profile.body, "utf8");
98
99
  }
99
- createInbox(run.sessionFile);
100
+ createInbox(run.runBase);
100
101
  await state.host.startAgent({
101
102
  name: run.name,
102
103
  paneId: pane.paneId,
@@ -118,6 +119,6 @@ export async function send(state: RunState, name: string, message: string): Prom
118
119
  run.busy = false;
119
120
  run.absentSince = undefined;
120
121
  wake(state);
121
- await enqueue(run.sessionFile, inboxMessage(message));
122
+ await enqueue(run.runBase, inboxMessage(message));
122
123
  return { state: "restarted", name: run.name, paneId: run.pane.paneId };
123
124
  }
package/src/run/start.ts CHANGED
@@ -6,6 +6,7 @@ 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 { runBaseOf, runsDir } from "./paths.ts";
9
10
  import { wake } from "./poll.ts";
10
11
  import { resolveProfile, resolveSkills } from "./resolve.ts";
11
12
  import { requireSlot } from "./slot.ts";
@@ -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,10 +61,13 @@ 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
67
  lastHandledSeq: 0,
64
68
  lastDeliveredText: null,
69
+ lastDeliveredSize: -1,
70
+ paneClosed: false,
65
71
  artifactSeq: 0,
66
72
  pollFailures: 0,
67
73
  busy: false,
@@ -75,6 +81,7 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
75
81
  run.paneLabel = paneLabel(task) || run.name;
76
82
  run.pane = await createPane(state, run, cwd, run.paneLabel);
77
83
  await mkdir(state.sessionsDir, { recursive: true });
84
+ await mkdir(runsDir(), { recursive: true });
78
85
 
79
86
  for (let retry = 1; ; retry++) {
80
87
  if (state.stopped) {
@@ -84,7 +91,7 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
84
91
  if (profile.systemPrompt !== "task") {
85
92
  await writeFile(current.identityFile, profile.body, "utf8");
86
93
  }
87
- await createInbox(current.sessionFile);
94
+ createInbox(current.runBase);
88
95
  try {
89
96
  await state.host.startAgent({
90
97
  name: run.name,
@@ -93,7 +100,7 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
93
100
  agentArgs: agentArgs(profile, current.identityFile, state.toolName, skillPaths),
94
101
  });
95
102
  // `agent start` 等到 idle 才算就绪,先入队会让第一轮抢跑并把它拖到超时(DEC-0023)。
96
- enqueue(current.sessionFile, `@${current.briefFile}`);
103
+ enqueue(current.runBase, `@${current.briefFile}`);
97
104
  break;
98
105
  } catch (error) {
99
106
  if (!(error instanceof HerdrHostError && error.code === "name_taken")) {
@@ -102,7 +109,7 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
102
109
  await Promise.all([
103
110
  rm(current.briefFile, { force: true }),
104
111
  rm(current.identityFile, { force: true }),
105
- removeInbox(current.sessionFile),
112
+ removeInbox(current.runBase),
106
113
  ]);
107
114
  if (retry >= NAME_ATTEMPTS) {
108
115
  throw new ToolError(
@@ -114,6 +121,7 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
114
121
  await state.host.renameTab({ tabId: run.pane.tabId, label: run.name });
115
122
  current = files(run.name);
116
123
  run.sessionFile = current.sessionFile;
124
+ run.runBase = current.runBase;
117
125
  }
118
126
  }
119
127
 
@@ -130,7 +138,7 @@ async function launch(state: RunState, profileName: string, task: string, rawCwd
130
138
  state.release(run);
131
139
  if (state.stopped && pane) {
132
140
  // 清理失败不改变结论:会话已在关闭,run 已被取消。
133
- await state.host.closeTabIfOnlyPane(pane).catch(() => "missing");
141
+ await state.host.closePane(pane.paneId).catch(() => undefined);
134
142
  }
135
143
  if (error instanceof ToolError) {
136
144
  throw error;
package/src/run/state.ts CHANGED
@@ -6,6 +6,7 @@ import type { ResultHandler, RunResult } from "./result.ts";
6
6
 
7
7
  export interface RunServiceDeps {
8
8
  host: HerdrHost;
9
+ sessionsDir: string;
9
10
  readLastAssistant: SessionReader;
10
11
  readExitReceipt: ExitReceiptReader;
11
12
  loadProfiles: () => ProfileCatalog;
@@ -37,10 +38,15 @@ export interface RunRecord {
37
38
  pane: RunPane | undefined;
38
39
  paneLabel: string;
39
40
  sessionFile: string;
41
+ // brief、identity、inbox、exit 回执、结果 artifact 共用的前缀。
42
+ runBase: string;
40
43
  cwd: string;
41
44
  autoExit: boolean;
42
45
  lastHandledSeq: number;
43
46
  lastDeliveredText: string | null;
47
+ // session 文件的字节数:只追加,变大就说明尾部换了一条消息。
48
+ lastDeliveredSize: number;
49
+ paneClosed: boolean;
44
50
  artifactSeq: number;
45
51
  read?: RunRead;
46
52
  pollFailures: number;
@@ -50,7 +56,6 @@ export interface RunRecord {
50
56
  }
51
57
 
52
58
  export interface RunState extends RunServiceDeps {
53
- sessionsDir: string;
54
59
  runs: RunRecord[];
55
60
  pending: Set<Promise<unknown>>;
56
61
  stopped: boolean;
@@ -10,9 +10,14 @@ export {
10
10
  writeExitReceipt,
11
11
  } from "./receipt.ts";
12
12
 
13
- export type SessionReader = (path: string) => SessionSnapshot;
13
+ export interface SessionRead extends SessionSnapshot {
14
+ // 读取时文件的字节数。session 只追加,所以它同时是尾部的身份。读不到时为 -1。
15
+ size: number;
16
+ }
14
17
 
15
- const UNREADABLE: SessionSnapshot = { text: null, pendingToolCall: false, empty: false, unreadable: true };
18
+ export type SessionReader = (path: string) => SessionRead;
19
+
20
+ const UNREADABLE: SessionRead = { text: null, pendingToolCall: false, empty: false, unreadable: true, size: -1 };
16
21
 
17
22
  export const readLastAssistant: SessionReader = (path) => {
18
23
  try {
@@ -20,10 +25,10 @@ export const readLastAssistant: SessionReader = (path) => {
20
25
  if (size > TAIL_WINDOW_BYTES) {
21
26
  const tail = parseLastAssistant(readTail(path, size));
22
27
  if (!tail.empty) {
23
- return tail;
28
+ return { ...tail, size };
24
29
  }
25
30
  }
26
- return parseLastAssistant(readFileSync(path, "utf8"));
31
+ return { ...parseLastAssistant(readFileSync(path, "utf8")), size };
27
32
  } catch {
28
33
  return { ...UNREADABLE };
29
34
  }
@@ -4,18 +4,18 @@ export interface ExitReceipt {
4
4
  reason: string;
5
5
  }
6
6
 
7
- export type ExitReceiptReader = (sessionFile: string) => ExitReceipt | null;
7
+ export type ExitReceiptReader = (base: string) => ExitReceipt | null;
8
8
 
9
- export type ExitReceiptWriter = (sessionFile: string, reason: string) => void;
9
+ export type ExitReceiptWriter = (base: string, reason: string) => void;
10
10
 
11
- function receiptFile(sessionFile: string): string {
12
- return `${sessionFile}.exit`;
11
+ function receiptFile(base: string): string {
12
+ return `${base}.exit`;
13
13
  }
14
14
 
15
- export const readExitReceipt: ExitReceiptReader = (sessionFile) => {
15
+ export const readExitReceipt: ExitReceiptReader = (base) => {
16
16
  let raw: string;
17
17
  try {
18
- raw = readFileSync(receiptFile(sessionFile), "utf8");
18
+ raw = readFileSync(receiptFile(base), "utf8");
19
19
  } catch (error) {
20
20
  if ((error as NodeJS.ErrnoException).code === "ENOENT") {
21
21
  return null;
@@ -34,6 +34,6 @@ export const readExitReceipt: ExitReceiptReader = (sessionFile) => {
34
34
  return { reason: parsed.reason };
35
35
  };
36
36
 
37
- export const writeExitReceipt: ExitReceiptWriter = (sessionFile, reason) => {
38
- writeFileSync(receiptFile(sessionFile), JSON.stringify({ reason }));
37
+ export const writeExitReceipt: ExitReceiptWriter = (base, reason) => {
38
+ writeFileSync(receiptFile(base), JSON.stringify({ reason }));
39
39
  };
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);
@@ -13,14 +13,14 @@ interface MessageSink {
13
13
  const UNKNOWN_TEXT: Record<UnknownReason, string> = {
14
14
  poll_failed: "status could not be read",
15
15
  no_result: "no result was read",
16
- close_failed: "result delivered, but the tab did not close",
16
+ close_failed: "result delivered, but the pane did not close",
17
17
  quitted: "the child exited without a result",
18
18
  pane_exited: "the pane exited without a result",
19
19
  };
20
20
 
21
21
  function resultText(result: RunResult): string {
22
22
  if (result.state === "unknown") {
23
- return `[subagent ${result.name}] ${UNKNOWN_TEXT[result.reason]}\n\nSession file: ${result.sessionFile}`;
23
+ return `[subagent ${result.name}] ${UNKNOWN_TEXT[result.reason]}`;
24
24
  }
25
25
  const artifact = result.artifact ? `\n\nFull result: ${result.artifact}` : "";
26
26
  const warning = result.warning ? `\n\n${result.warning}` : "";
package/src/tool/text.ts CHANGED
@@ -2,10 +2,10 @@ import type { Config } from "../config/index.ts";
2
2
  import type { Profile } from "../profile/index.ts";
3
3
  import { profileLabel } from "../run/index.ts";
4
4
 
5
- const DEFAULT_DESCRIPTION = "Run subagents and send them messages.";
5
+ const DEFAULT_DESCRIPTION =
6
+ "Use run when a task is self-contained and long-running. Use send to pass information to a subagent.";
6
7
  const DEFAULT_SNIPPET = "";
7
8
  const DEFAULT_GUIDELINES = [
8
- "The parent handles user interaction, cross-task synthesis, and decisions; subagents execute.",
9
9
  "run only starts; it does not wait. The result arrives later as a message.",
10
10
  "send only delivers; no state tracking.",
11
11
  "Available profiles:\n{{profiles}}",