pi-herdr-subagents-lite 0.8.0 → 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/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
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.9.0 — 2026-11-12
6
+
7
+ - **BREAKING**:完成不再从 session 尾部推断。子代理在每个 `agent_settled` 写一个回合事件(`<runBase>.turns/<n>.json`),父代理只认这个文件。失败轮、中断轮不会再被当成完成;消息明确写 `failed` / `interrupted`,并附已有部分文本。
8
+ - **BREAKING**:子代理不再自杀。`auto-exit` 变成父代理的关闭判据:`done` 且没有活着的子代理才关。删掉 `PI_SUBAGENT_AUTO_EXIT`。
9
+ - **BREAKING**:配置项 `pollIntervalMs` 与 `idlePollIntervalMs` 删除,改为 `livenessPollMs`(默认 15000)。`closeChildrenOn` 默认改为 `["quit", "reload"]`,新增 `closeOnFailure`(默认 false)。
10
+ - 不再每秒起 `herdr agent list` 进程。回合用 500ms 一次本地目录扫描;存活只对进行中的 run 每 15 秒对账,连续三次缺席才判失去联系。
11
+ - 并发上限只数进行中的回合。收工等 `send` 的子代理不再占槽。
12
+ - 关 pane 重试 3 次、间隔 250ms;失败只通知一次。
13
+
5
14
  ## 0.8.0 — 2026-11-03
6
15
 
7
16
  - 模型不再看到子 session 路径与 pane id:`run` 与 `send` 的工具返回只剩 `state` 与 `name`,`paneId` 与 `sessionFile` 留在 `details`。`unknown` 结果消息不再附 `Session file:`。`send` 的错误只报子代理名。目的是不让父代理顺着路径去读子会话正文。
package/README.md CHANGED
@@ -54,20 +54,20 @@ The block below lists every key. Each value is the default.
54
54
  "toolName": "subagent",
55
55
  // Default "herdr". A plain name resolves from PATH; an absolute path pins a version.
56
56
  "herdrBin": "herdr",
57
- // Default 16, range 1 and up. At the limit run returns max_concurrent. A child with auto-exit: false keeps its slot after it settles.
57
+ // Default 16, range 1 and up. At the limit run returns max_concurrent. Only a running turn holds a slot.
58
58
  "maxConcurrent": 16,
59
59
  // Default 16384, range 1024 to 1048576. A longer text goes to an artifact file. The message keeps a truncated head and the path.
60
60
  "maxResultChars": 16384,
61
61
  // Default 500, range 0 to 10000 milliseconds. 0 = deliver each result at once. A larger value merges more results.
62
62
  "aggregateWindowMs": 500,
63
- // Default empty = never close. Values: new, resume, fork, quit, reload. A listed reason closes the child tabs on parent shutdown.
64
- "closeChildrenOn": [],
63
+ // Default ["quit", "reload"]. Values: new, resume, fork, quit, reload. A listed reason closes the child panes on parent shutdown.
64
+ "closeChildrenOn": ["quit", "reload"],
65
+ // Default false. true = close the pane after a failed or interrupted turn. false keeps it so send can resume.
66
+ "closeOnFailure": false,
65
67
  // Default 250, range 50 to 5000 milliseconds. A larger value wakes less often and delivers later.
66
68
  "inboxPollMs": 250,
67
- // Default 1000, range 100 to 60000 milliseconds. Use while a child works or blocks, or within 30 s of run or send.
68
- "pollIntervalMs": 1000,
69
- // Default 8000, range 100 to 60000 milliseconds. Use when every live child only waits for send. A larger value notices a dead pane later.
70
- "idlePollIntervalMs": 8000,
69
+ // Default 15000, range 1000 to 300000 milliseconds. How often a running child is checked for liveness. Three absences in a row mark it lost.
70
+ "livenessPollMs": 15000,
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.
@@ -134,7 +134,7 @@ skills: ""
134
134
  # task: body is the task text, no identity file
135
135
  system-prompt: append
136
136
 
137
- # Shut down and close the tab when settled. It waits while a prompt is open or the inbox has messages
137
+ # Close the pane after this run's done turn. Leave it false to keep the child resumable with send
138
138
  auto-exit: true
139
139
 
140
140
  # true = hidden from the guidelines; an explicit run still works
@@ -167,10 +167,12 @@ Thank you for the code.
167
167
 
168
168
  | Document | Content |
169
169
  |---|---|
170
- | [docs/specs/0001-v1-contract.md](docs/specs/0001-v1-contract.md) | The v1 contract |
171
- | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Module boundaries, dependency direction, test seams |
172
- | [docs/modules/](docs/modules/) | Usage and trade-offs per module |
173
- | [docs/GLOSSARY.md](docs/GLOSSARY.md) | The only source for terms |
170
+ | [ARCHITECTURE](docs/ARCHITECTURE.md) | Module boundaries, dependency direction, test seams |
171
+ | [GLOSSARY](docs/GLOSSARY.md) | The only source for terms |
172
+ | [Modules](docs/modules/) | Usage and trade-offs per module |
173
+ | [Decisions](docs/decisions/) | One file per decision |
174
+ | [Spec](docs/specs/0001-v1-contract.md) | The v1 contract |
175
+ | [Research](docs/research/) | Measurements of herdr and pi |
174
176
  | [CHANGELOG.md](CHANGELOG.md) | Release notes |
175
177
 
176
178
  ## License
package/README.zh-CN.md CHANGED
@@ -54,20 +54,20 @@ pi -e /path/to/pi-herdr-subagents-lite/src/index.ts # 只对当前进程生效
54
54
  "toolName": "subagent",
55
55
  // 默认 "herdr"。裸名从 PATH 解析。绝对路径锁定版本。
56
56
  "herdrBin": "herdr",
57
- // 默认 16,下限 1。到上限时 run 返回 max_concurrent。auto-exit: false 的子代理收工后仍占槽。
57
+ // 默认 16,下限 1。到上限时 run 返回 max_concurrent。只有进行中的回合占槽。
58
58
  "maxConcurrent": 16,
59
59
  // 默认 16384,范围 1024 到 1048576。超上限时全文落 artifact 文件。消息里留截断的头和路径。
60
60
  "maxResultChars": 16384,
61
61
  // 默认 500,范围 0 到 10000,单位毫秒。0 = 逐条立即投递。调大合并更多结果。
62
62
  "aggregateWindowMs": 500,
63
- // 默认空 = 从不关。取值:new、resume、fork、quit、reload。列出的原因会在父会话退出时关掉子 tab。
64
- "closeChildrenOn": [],
63
+ // 默认 ["quit", "reload"]。取值:new、resume、fork、quit、reload。列出的原因会在父会话退出时关掉子 pane。
64
+ "closeChildrenOn": ["quit", "reload"],
65
+ // 默认 false。true = 失败或中断的回合结束后关 pane。false 留着,send 可以续。
66
+ "closeOnFailure": false,
65
67
  // 默认 250,范围 50 到 5000,单位毫秒。调大省唤醒,投递变慢。
66
68
  "inboxPollMs": 250,
67
- // 默认 1000,范围 100 到 60000,单位毫秒。子代理在 working 或 blocked 时用它,刚 run / send 的 30 秒内也用它。
68
- "pollIntervalMs": 1000,
69
- // 默认 8000,范围 100 到 60000,单位毫秒。所有 live 子代理都只在等 send 时用它。调大后,发现 pane 消失更晚。
70
- "idlePollIntervalMs": 8000,
69
+ // 默认 15000,范围 1000 到 300000,单位毫秒。多久查一次进行中的子代理还活着没有。连续三次缺席判为失去联系。
70
+ "livenessPollMs": 15000,
71
71
  // 工具文案覆盖。每个键默认未设置,用下面这份内置文案。
72
72
  "prompts": {
73
73
  // 替换内置描述。
@@ -134,7 +134,7 @@ skills: ""
134
134
  # task:正文就是任务文本,不写身份文件
135
135
  system-prompt: append
136
136
 
137
- # 收工后自行退出并关掉 tab。有打开的对话框或 inbox 待投递时会等
137
+ # 这个 run 的 done 回合结束后关掉 pane。false 则留着,send 还能续
138
138
  auto-exit: true
139
139
 
140
140
  # true = 不出现在 guidelines 的 profile 列表里。显式 run 仍然可用
@@ -167,10 +167,12 @@ cd <agent-dir>/pi-herdr-subagents-lite/profiles && cp examples/worker.md worker.
167
167
 
168
168
  | 文档 | 内容 |
169
169
  |---|---|
170
- | [docs/specs/0001-v1-contract.md](docs/specs/0001-v1-contract.md) | v1 契约 |
171
- | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | 模块边界、依赖方向、测试 seam |
172
- | [docs/modules/](docs/modules/) | 各模块的用法与取舍 |
173
- | [docs/GLOSSARY.md](docs/GLOSSARY.md) | 术语唯一来源 |
170
+ | [ARCHITECTURE](docs/ARCHITECTURE.md) | 模块边界、依赖方向、测试 seam |
171
+ | [GLOSSARY](docs/GLOSSARY.md) | 术语唯一来源 |
172
+ | [Modules](docs/modules/) | 各模块的用法与取舍 |
173
+ | [Decisions](docs/decisions/) | 一条决策一份文件 |
174
+ | [Spec](docs/specs/0001-v1-contract.md) | v1 契约 |
175
+ | [Research](docs/research/) | herdr 与 pi 的实测记录 |
174
176
  | [CHANGELOG.md](CHANGELOG.md) | 发布记录 |
175
177
 
176
178
  ## License
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-herdr-subagents-lite",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Run pi subagents in herdr panes.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -40,8 +40,8 @@ export interface Config {
40
40
  aggregateWindowMs: number;
41
41
  closeChildrenOn: ShutdownReason[];
42
42
  inboxPollMs: number;
43
- pollIntervalMs: number;
44
- idlePollIntervalMs: number;
43
+ livenessPollMs: number;
44
+ closeOnFailure: boolean;
45
45
  prompts: PromptOverrides;
46
46
  bridge: { enabled: boolean; blockedOn: BlockedKind[] };
47
47
  }
@@ -75,10 +75,10 @@ function parse(raw: Raw, file: string): Config {
75
75
  maxConcurrent: integer(top, "maxConcurrent", 16, 1, Number.POSITIVE_INFINITY),
76
76
  maxResultChars: integer(top, "maxResultChars", 16384, 1024, 1048576),
77
77
  aggregateWindowMs: integer(top, "aggregateWindowMs", 500, 0, 10000),
78
- closeChildrenOn: enumList(top, "closeChildrenOn", SHUTDOWN_REASONS, []),
78
+ closeChildrenOn: enumList(top, "closeChildrenOn", SHUTDOWN_REASONS, ["quit", "reload"]),
79
+ closeOnFailure: boolean(top, "closeOnFailure", false),
79
80
  inboxPollMs: integer(top, "inboxPollMs", 250, 50, 5000),
80
- pollIntervalMs: integer(top, "pollIntervalMs", 1000, 100, 60000),
81
- idlePollIntervalMs: integer(top, "idlePollIntervalMs", 8000, 100, 60000),
81
+ livenessPollMs: integer(top, "livenessPollMs", 15000, 1000, 300000),
82
82
  prompts: promptOverrides(top),
83
83
  bridge: {
84
84
  enabled: boolean(bridge, "enabled", true),
@@ -6,9 +6,9 @@ export const CONFIG_KEYS = [
6
6
  "maxResultChars",
7
7
  "aggregateWindowMs",
8
8
  "closeChildrenOn",
9
+ "closeOnFailure",
9
10
  "inboxPollMs",
10
- "pollIntervalMs",
11
- "idlePollIntervalMs",
11
+ "livenessPollMs",
12
12
  "prompts",
13
13
  "bridge",
14
14
  ];
@@ -6,16 +6,15 @@ 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
8
  import { childSessionsDir, createRunService, type RunService, runBaseOf } from "../run/index.ts";
9
- import type { ExitReceiptReader, ExitReceiptWriter, SessionReader } from "../session-file/index.ts";
9
+ import type { SessionTailReader } from "../session-file/index.ts";
10
10
  import { createTool, type ResultMessage, type SubagentTool, sendResults } from "../tool/index.ts";
11
- import { watchAutoExit } from "./auto-exit.ts";
11
+ import type { TurnEntry } from "../turn/index.ts";
12
+ import { watchReport } from "./report.ts";
12
13
  import { type ShutdownHandler, watchShutdown } from "./shutdown.ts";
13
14
 
14
15
  export interface ExtensionDeps {
15
16
  createHost: (config: Config) => HerdrHost;
16
- readLastAssistant: SessionReader;
17
- readExitReceipt: ExitReceiptReader;
18
- writeExitReceipt: ExitReceiptWriter;
17
+ readSessionTail: SessionTailReader;
19
18
  loadConfig: () => Config;
20
19
  loadProfiles: (sources: ProfileSources) => ProfileCatalog;
21
20
  }
@@ -23,7 +22,10 @@ export interface ExtensionDeps {
23
22
  export interface SessionContext {
24
23
  cwd: string;
25
24
  isProjectTrusted(): boolean;
26
- sessionManager: { getSessionFile(): string | undefined };
25
+ sessionManager: {
26
+ getSessionFile(): string | undefined;
27
+ getBranch(): TurnEntry[];
28
+ };
27
29
  isIdle(): boolean;
28
30
  ui: { notify(message: string, type?: "info" | "warning" | "error"): void };
29
31
  shutdown(): void;
@@ -32,7 +34,7 @@ export interface SessionContext {
32
34
  export type { SubagentTool };
33
35
 
34
36
  type SessionStartHandler = (event: SessionStartEvent, ctx: SessionContext) => void;
35
- type SettledHandler = (event: { type: "agent_settled" }, ctx: SessionContext) => void;
37
+ type SettledHandler = (event: { type: "agent_settled"; aborted: boolean }, ctx: SessionContext) => void;
36
38
  type PromptHandler = (event: { kind: BlockedKind; title?: string }) => void;
37
39
 
38
40
  export interface ExtensionRegistrar {
@@ -56,7 +58,7 @@ export function createExtension(deps: ExtensionDeps): (pi: ExtensionRegistrar) =
56
58
  let stopPump: (() => void) | undefined;
57
59
  let inboxFailures = 0;
58
60
  createBridge(pi, config.bridge);
59
- const autoExit = watchAutoExit(pi);
61
+ watchReport(pi, { activeChildren: () => service?.active().length ?? 0 });
60
62
 
61
63
  const stopInbox = () => {
62
64
  stopPump?.();
@@ -65,7 +67,6 @@ export function createExtension(deps: ExtensionDeps): (pi: ExtensionRegistrar) =
65
67
 
66
68
  watchShutdown(pi, {
67
69
  config,
68
- writeExitReceipt: deps.writeExitReceipt,
69
70
  stopInbox,
70
71
  takeService() {
71
72
  const current = service;
@@ -111,24 +112,29 @@ export function createExtension(deps: ExtensionDeps): (pi: ExtensionRegistrar) =
111
112
  service = createRunService({
112
113
  host,
113
114
  sessionsDir: childSessionsDir(ctx.sessionManager.getSessionFile()),
114
- readLastAssistant: deps.readLastAssistant,
115
- readExitReceipt: deps.readExitReceipt,
115
+ readSessionTail: deps.readSessionTail,
116
116
  loadProfiles: () => deps.loadProfiles(sources),
117
117
  trusted: sources.trusted,
118
118
  maxConcurrent: config.maxConcurrent,
119
119
  maxResultChars: config.maxResultChars,
120
120
  aggregateWindowMs: config.aggregateWindowMs,
121
- pollIntervalMs: config.pollIntervalMs,
122
- idlePollIntervalMs: config.idlePollIntervalMs,
121
+ livenessPollMs: config.livenessPollMs,
122
+ closeOnFailure: config.closeOnFailure,
123
123
  toolName: config.toolName,
124
- onDeliveryError: (error) => ctx.ui.notify(`subagent result not delivered: ${errorText(error)}`, "error"),
124
+ onProblem: (message) => ctx.ui.notify(message, "error"),
125
125
  });
126
126
  service.onResult((results) => sendResults(pi, results));
127
127
  };
128
128
 
129
+ const currentService = (): RunService => {
130
+ if (!service) {
131
+ throw new Error("subagent service is not started");
132
+ }
133
+ return service;
134
+ };
135
+
129
136
  pi.on("session_start", (_event, ctx) => {
130
137
  stopInbox();
131
- autoExit.reset();
132
138
  const sources = { cwd: ctx.cwd, trusted: ctx.isProjectTrusted() };
133
139
  startService(sources, ctx);
134
140
  if (config.enabled) {
@@ -137,12 +143,5 @@ export function createExtension(deps: ExtensionDeps): (pi: ExtensionRegistrar) =
137
143
  }
138
144
  startInbox(ctx);
139
145
  });
140
-
141
- const currentService = (): RunService => {
142
- if (!service) {
143
- throw new Error("subagent service is not started");
144
- }
145
- return service;
146
- };
147
146
  };
148
147
  }
@@ -0,0 +1,43 @@
1
+ import { errorText } from "../error/index.ts";
2
+ import { hasInbox } from "../inbox/index.ts";
3
+ import { runBaseOf } from "../run/index.ts";
4
+ import { classifyTurn, lastTurnOf, nextTurn, writeTurn } from "../turn/index.ts";
5
+ import type { ExtensionRegistrar } from "./index.ts";
6
+
7
+ export interface ReportDeps {
8
+ activeChildren: () => number;
9
+ }
10
+
11
+ // 子代理唯一的结果出口:每个结束的回合写一个回合事件。
12
+ export function watchReport(pi: ExtensionRegistrar, deps: ReportDeps): void {
13
+ pi.on("agent_settled", (event, ctx) => {
14
+ const sessionFile = ctx.sessionManager.getSessionFile();
15
+ if (sessionFile === undefined) {
16
+ return;
17
+ }
18
+ const base = runBaseOf(sessionFile);
19
+ if (!hasInbox(base)) {
20
+ return;
21
+ }
22
+ try {
23
+ const slice = lastTurnOf(ctx.sessionManager.getBranch());
24
+ const verdict = classifyTurn({
25
+ stopReason: slice.stopReason,
26
+ pendingToolCall: slice.pendingToolCall,
27
+ aborted: event.aborted || !slice.found,
28
+ errorMessage: slice.errorMessage,
29
+ });
30
+ writeTurn(base, {
31
+ turn: nextTurn(base),
32
+ outcome: verdict.outcome,
33
+ stopReason: slice.stopReason ?? "",
34
+ ...(verdict.errorMessage === undefined ? {} : { errorMessage: verdict.errorMessage }),
35
+ ...(slice.text === null ? {} : { text: slice.text }),
36
+ children: deps.activeChildren(),
37
+ at: Date.now(),
38
+ });
39
+ } catch (error) {
40
+ ctx.ui.notify(`subagent turn not reported: ${errorText(error)}`, "error");
41
+ }
42
+ });
43
+ }
@@ -1,7 +1,8 @@
1
1
  import type { Config, ShutdownReason } from "../config/index.ts";
2
+ import { errorText } from "../error/index.ts";
2
3
  import { hasInbox } from "../inbox/index.ts";
3
4
  import { type RunService, runBaseOf } from "../run/index.ts";
4
- import type { ExitReceiptWriter } from "../session-file/index.ts";
5
+ import { nextTurn, writeTurn } from "../turn/index.ts";
5
6
  import type { ExtensionRegistrar, SessionContext } from "./index.ts";
6
7
 
7
8
  export type ShutdownHandler = (
@@ -11,7 +12,6 @@ export type ShutdownHandler = (
11
12
 
12
13
  export interface ShutdownDeps {
13
14
  config: Config;
14
- writeExitReceipt: ExitReceiptWriter;
15
15
  stopInbox(): void;
16
16
  takeService(): RunService | undefined;
17
17
  }
@@ -22,8 +22,18 @@ export function watchShutdown(pi: ExtensionRegistrar, deps: ShutdownDeps): void
22
22
  const closing = deps.takeService();
23
23
  const sessionFile = ctx.sessionManager.getSessionFile();
24
24
  const base = sessionFile === undefined ? undefined : runBaseOf(sessionFile);
25
- if (base !== undefined && hasInbox(base)) {
26
- deps.writeExitReceipt(base, event.reason);
25
+ if (base !== undefined && event.reason === "quit" && hasInbox(base)) {
26
+ try {
27
+ writeTurn(base, {
28
+ turn: nextTurn(base),
29
+ outcome: "quit",
30
+ stopReason: "quit",
31
+ children: 0,
32
+ at: Date.now(),
33
+ });
34
+ } catch (error) {
35
+ ctx.ui.notify(`subagent exit not reported: ${errorText(error)}`, "error");
36
+ }
27
37
  }
28
38
  if (closing && deps.config.closeChildrenOn.includes(event.reason)) {
29
39
  const { failed } = await closing.closeChildren();
@@ -4,7 +4,6 @@ export type AgentStatus = "idle" | "working" | "blocked" | "done" | "unknown";
4
4
 
5
5
  export interface AgentSnapshot {
6
6
  status: AgentStatus;
7
- completionSeq: number;
8
7
  }
9
8
 
10
9
  export interface AgentEntry extends AgentSnapshot {
@@ -22,8 +21,6 @@ export interface StartAgentInput {
22
21
 
23
22
  interface AgentInfo {
24
23
  agent_status: AgentStatus;
25
- completion_seq?: number | null;
26
- state_change_seq?: number;
27
24
  name?: string | null;
28
25
  pane_id: string;
29
26
  agent_session?: { kind?: string; value?: string } | null;
@@ -65,7 +62,6 @@ export function createAgentCommands(exec: ExecHerdr) {
65
62
  paneId: agent.pane_id,
66
63
  sessionFile: sessionPath(agent),
67
64
  status: agent.agent_status,
68
- completionSeq: agent.completion_seq ?? agent.state_change_seq ?? 0,
69
65
  }));
70
66
  },
71
67
  };
package/src/herdr/pane.ts CHANGED
@@ -8,23 +8,17 @@ export interface CreatedTab {
8
8
  export interface CreateTabInput {
9
9
  cwd: string;
10
10
  label: string;
11
- env: Record<string, string>;
12
11
  }
13
12
 
14
13
  export interface CreateWorkspaceInput {
15
14
  cwd: string;
16
15
  label: string;
17
- env: Record<string, string>;
18
16
  }
19
17
 
20
18
  export interface CreatedWorkspace extends CreatedTab {
21
19
  workspaceId: string;
22
20
  }
23
21
 
24
- function envArgs(env: Record<string, string>): string[] {
25
- return Object.entries(env).flatMap(([key, value]) => ["--env", `${key}=${value}`]);
26
- }
27
-
28
22
  export interface RenameTabInput {
29
23
  tabId: string;
30
24
  label: string;
@@ -49,7 +43,7 @@ interface PaneInfo {
49
43
 
50
44
  export function createPaneCommands(exec: ExecHerdr) {
51
45
  return {
52
- async createWorkspace({ cwd, label, env }: CreateWorkspaceInput): Promise<CreatedWorkspace> {
46
+ async createWorkspace({ cwd, label }: CreateWorkspaceInput): Promise<CreatedWorkspace> {
53
47
  const result = await exec<{ workspace: WorkspaceInfo; tab: TabInfo; root_pane: PaneInfo }>([
54
48
  "workspace",
55
49
  "create",
@@ -57,7 +51,6 @@ export function createPaneCommands(exec: ExecHerdr) {
57
51
  cwd,
58
52
  "--label",
59
53
  label,
60
- ...envArgs(env),
61
54
  "--no-focus",
62
55
  ]);
63
56
  return {
@@ -67,7 +60,7 @@ export function createPaneCommands(exec: ExecHerdr) {
67
60
  };
68
61
  },
69
62
 
70
- async createTab({ cwd, label, env }: CreateTabInput): Promise<CreatedTab> {
63
+ async createTab({ cwd, label }: CreateTabInput): Promise<CreatedTab> {
71
64
  const result = await exec<{ tab: TabInfo; root_pane: PaneInfo }>([
72
65
  "tab",
73
66
  "create",
@@ -75,7 +68,6 @@ export function createPaneCommands(exec: ExecHerdr) {
75
68
  cwd,
76
69
  "--label",
77
70
  label,
78
- ...envArgs(env),
79
71
  "--no-focus",
80
72
  ]);
81
73
  return { tabId: result.tab.tab_id, paneId: result.root_pane.pane_id };
package/src/index.ts CHANGED
@@ -3,17 +3,15 @@ import { loadConfig } from "./config/index.ts";
3
3
  import { createExtension } from "./extension/index.ts";
4
4
  import { createHerdrHost } from "./herdr/index.ts";
5
5
  import { agentDir, globalProfilesDir, loadProfiles, seedExampleProfile } from "./profile/index.ts";
6
- import { readExitReceipt, readLastAssistant, writeExitReceipt } from "./session-file/index.ts";
6
+ import { readSessionTail } from "./session-file/index.ts";
7
7
 
8
8
  seedExampleProfile(globalProfilesDir());
9
9
 
10
10
  const extension: ExtensionFactory = createExtension({
11
11
  createHost: (config) => createHerdrHost(config.herdrBin),
12
- readLastAssistant,
13
- readExitReceipt,
12
+ readSessionTail,
14
13
  loadConfig: () => loadConfig(agentDir()),
15
14
  loadProfiles,
16
- writeExitReceipt,
17
15
  });
18
16
 
19
17
  export default extension;
@@ -1,5 +1,6 @@
1
1
  export interface Aggregator<T> {
2
- push(item: T): Promise<void>;
2
+ // 返回是否真的投递成功。批量窗口内的条目在 flush 之后才结算。
3
+ push(item: T): Promise<boolean>;
3
4
  stop(): void;
4
5
  }
5
6
 
@@ -9,43 +10,54 @@ export interface AggregatorOptions<T> {
9
10
  onError: (error: unknown) => void;
10
11
  }
11
12
 
13
+ interface Queued<T> {
14
+ item: T;
15
+ resolve: (delivered: boolean) => void;
16
+ }
17
+
12
18
  export function createAggregator<T>({ windowMs, deliver, onError }: AggregatorOptions<T>): Aggregator<T> {
13
- let pending: T[] = [];
19
+ let pending: Array<Queued<T>> = [];
14
20
  let timer: ReturnType<typeof setTimeout> | undefined;
15
21
  let stopped = false;
16
22
 
17
- const send = async (items: T[]) => {
23
+ const send = async (items: Array<Queued<T>>) => {
24
+ let delivered = true;
18
25
  try {
19
- await deliver(items);
26
+ await deliver(items.map((entry) => entry.item));
20
27
  } catch (error) {
28
+ delivered = false;
21
29
  onError(error);
22
30
  }
31
+ for (const entry of items) {
32
+ entry.resolve(delivered);
33
+ }
23
34
  };
24
35
 
25
36
  const flush = () => {
26
37
  timer = undefined;
27
- if (pending.length === 0) {
28
- return;
29
- }
30
38
  const items = pending;
31
39
  pending = [];
32
- void send(items);
40
+ if (items.length > 0) {
41
+ void send(items);
42
+ }
33
43
  };
34
44
 
35
45
  return {
36
46
  push(item) {
37
47
  if (stopped) {
38
- return Promise.resolve();
39
- }
40
- if (windowMs === 0) {
41
- return send([item]);
48
+ return Promise.resolve(false);
42
49
  }
43
- pending.push(item);
44
- if (timer === undefined) {
45
- timer = setTimeout(flush, windowMs);
46
- timer.unref?.();
47
- }
48
- return Promise.resolve();
50
+ return new Promise<boolean>((resolve) => {
51
+ if (windowMs === 0) {
52
+ void send([{ item, resolve }]);
53
+ return;
54
+ }
55
+ pending.push({ item, resolve });
56
+ if (timer === undefined) {
57
+ timer = setTimeout(flush, windowMs);
58
+ timer.unref?.();
59
+ }
60
+ });
49
61
  },
50
62
  stop() {
51
63
  stopped = true;
@@ -53,6 +65,9 @@ export function createAggregator<T>({ windowMs, deliver, onError }: AggregatorOp
53
65
  clearTimeout(timer);
54
66
  timer = undefined;
55
67
  }
68
+ for (const entry of pending) {
69
+ entry.resolve(false);
70
+ }
56
71
  pending = [];
57
72
  },
58
73
  };
package/src/run/close.ts CHANGED
@@ -1,19 +1,47 @@
1
1
  import { errorText } from "../error/index.ts";
2
- import type { RunResult } from "./result.ts";
2
+ import { HerdrHostError } from "../herdr/index.ts";
3
+ import type { Turn } from "../turn/index.ts";
3
4
  import type { RunRecord, RunState } from "./state.ts";
4
5
 
5
- export function shouldClose(run: RunRecord, result: RunResult): boolean {
6
- return result.state === "done" && run.autoExit;
6
+ const CLOSE_ATTEMPTS = 3;
7
+ const CLOSE_RETRY_MS = 250;
8
+
9
+ // 关闭判据只看回合结果与子代理是否还有自己的子代理。
10
+ export function shouldClose(state: RunState, run: RunRecord, turn: Turn): boolean {
11
+ if (run.pane === undefined || run.paneClosed) {
12
+ return false;
13
+ }
14
+ if (turn.outcome === "done") {
15
+ return run.autoExit && turn.children === 0;
16
+ }
17
+ if (turn.outcome === "quit") {
18
+ return true;
19
+ }
20
+ return state.closeOnFailure;
7
21
  }
8
22
 
9
- // 只关自己记下的 pane,所以不需要先确认 tab 里有什么。pane 已经不在了也算关掉。
23
+ // 只关自己记下的 pane。pane 已经不在了也算关掉。
10
24
  export async function closeRunPane(state: RunState, run: RunRecord): Promise<void> {
11
25
  const pane = run.pane;
12
- if (pane === undefined) {
26
+ if (pane === undefined || run.paneClosed) {
13
27
  return;
14
28
  }
15
- await state.host.closePane(pane.paneId);
16
- run.paneClosed = true;
29
+ for (let attempt = 1; ; attempt += 1) {
30
+ try {
31
+ await state.host.closePane(pane.paneId);
32
+ run.paneClosed = true;
33
+ return;
34
+ } catch (error) {
35
+ if (error instanceof HerdrHostError && error.code === "pane_not_found") {
36
+ run.paneClosed = true;
37
+ return;
38
+ }
39
+ if (attempt >= CLOSE_ATTEMPTS) {
40
+ throw error;
41
+ }
42
+ await state.delay(CLOSE_RETRY_MS);
43
+ }
44
+ }
17
45
  }
18
46
 
19
47
  export interface CloseChildrenResult {
@@ -26,7 +54,7 @@ interface CloseOutcome {
26
54
  }
27
55
 
28
56
  export async function closeRuns(state: RunState, runs: RunRecord[]): Promise<CloseChildrenResult> {
29
- const targets = runs.filter((run) => run.pane !== undefined);
57
+ const targets = runs.filter((run) => run.pane !== undefined && !run.paneClosed);
30
58
  const outcomes: CloseOutcome[] = await Promise.all(
31
59
  targets.map(async (run) => {
32
60
  try {