@hcflabs/pi-herdr-tools 1.9.0 → 1.10.1

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/README.md CHANGED
@@ -60,6 +60,8 @@ Both commands require `HERDR_ENV=1` and `HERDR_PANE_ID`. Pane, session-path, and
60
60
 
61
61
  Clone tabs keep the current working directory. Worktree clones use the new checkout. Pi starts with `--session <absolute-clone-file>`; only successful launches change focus.
62
62
 
63
+ A tab or worktree creation returns before the new pane shell reads input. Each clone waits until the shell owns the foreground and draws its prompt. Only then does it start Pi. A shell that still runs startup files can lose the Enter key of a long command.
64
+
63
65
  Worktree creation uses `herdr worktree create --workspace <current-workspace> --no-focus`, or the repository's parent workspace when already in a linked worktree. Herdr creates missing branches from `HEAD`, with checkouts under `worktrees.directory` in grouped workspaces. Clones and handoffs use an extra unfocused tab if a layout plugin such as `herdr-plus` occupies the root pane.
64
66
 
65
67
  ### Worktree handoff
@@ -68,12 +70,13 @@ Run `/handoff-worktree Fix the flaky login test`. The agent collects missing fac
68
70
 
69
71
  The tool registers only with `HERDR_ENV=1`. It also requires `HERDR_PANE_ID` and local `main`. A handoff has no checked integration: the new agent works without supervision. Delegated subagents cannot use the tool.
70
72
 
71
- The tool selects the repository in one of two ways:
73
+ The tool selects the repository in one of three ways:
72
74
 
73
75
  - Without `repo`, the current directory and the pane workspace must be in the same Git repository.
74
- - With `repo`, the tool uses that child repository of the Pi working directory. Use it when Pi runs in a parent directory that holds many repositories. The current workspace does not need a Git checkout.
76
+ - Without `repo`, when the pane workspace has no Git checkout, the Pi working directory is the repository. This works only when the working directory is a Git top-level directory. The tool then uses `--cwd <repository>`.
77
+ - With `repo`, the tool uses that repository below the Pi working directory. Use it when Pi runs in a parent directory that holds many repositories. Use `.` for the working directory itself. The current workspace does not need a Git checkout.
75
78
 
76
- The tool never selects a child repository automatically. All parameters must be non-empty strings:
79
+ The tool never selects a child repository automatically. When `repo` is needed, the error names the `repo` parameter. It lists at most 20 repository paths that it found below the Pi working directory. All parameters must be non-empty strings:
77
80
 
78
81
  | Parameter | Requirement |
79
82
  | --- | --- |
@@ -81,9 +84,9 @@ The tool never selects a child repository automatically. All parameters must be
81
84
  | `label` | Workspace label. |
82
85
  | `agentName` | Unique agent name matching `^[a-z][a-z0-9_-]{0,31}$`. |
83
86
  | `prompt` | Self-contained task prompt. |
84
- | `repo` | Optional. A Git top-level directory, relative to the Pi working directory. It must not contain `..` or resolve outside that directory. A subdirectory of a repository fails. |
87
+ | `repo` | Optional. A Git top-level directory, relative to the Pi working directory. `.` names the working directory. It must not contain `..` or resolve outside that directory. A subdirectory of a repository fails. |
85
88
 
86
- After validation, the tool runs `herdr worktree create --workspace <parent> --branch <branch> --base main --label <label> --no-focus`. With `repo`, it uses `--cwd <repository>` instead of `--workspace <parent>`. Herdr then opens the primary workspace of the repository, or creates it, and does not close it later. It starts Pi without session arguments. It submits `herdr agent prompt <agentName> <prompt> --wait --until working --timeout 30000`, with the prompt as one argument, not a shell command or file. The result includes workspace ID, tab, pane, branch, checkout path, agent name, and `repo` when set.
89
+ After validation, the tool runs `herdr worktree create --workspace <parent> --branch <branch> --base main --label <label> --no-focus`. With `repo`, it uses `--cwd <repository>` instead of `--workspace <parent>`. Herdr then opens the primary workspace of the repository, or creates it, and does not close it later. The tool waits until the new pane shell reads input, then starts Pi without session arguments. It submits `herdr agent prompt <agentName> <prompt> --wait --until working --timeout 30000`, with the prompt as one argument, not a shell command or file. The result includes workspace ID, tab, pane, branch, checkout path, agent name, and `repo` when set.
87
90
 
88
91
  ### Command panes
89
92
 
@@ -117,6 +120,8 @@ The side-thread model receives Main's fixed, compaction-aware context snapshot.
117
120
 
118
121
  Run `/btw merge Apply the smallest safe fix` after the answer. The merge request contains user and assistant text, without tool payloads. Pending delivery survives shutdown until consumption or 24-hour stale cleanup. Once idle and authenticated, Main appends the transcript without starting a turn, then submits the prompt.
119
122
 
123
+ `/btw` splits the pane, waits until the new pane shell reads input, and then starts Pi. A split returns before its shell is ready.
124
+
120
125
  ### Titles
121
126
 
122
127
  Automatic titles ignore extension-injected, empty, and image-only prompts. Expanded skill and prompt-template text starts background generation without delaying the reply. English, sentence-case display titles usually have two or three words; limits are four words and 20 characters.
@@ -198,6 +203,7 @@ Clones are separate session files in the Pi-selected session directory. Each con
198
203
  | Agent start requested | An ambiguous launch retains targets and session files. Inspect reported IDs. |
199
204
  | Clone focus failure | Pi already started. Focus its tab manually. |
200
205
  | Handoff validation failure | No worktree exists. Correct the reported requirement. |
206
+ | Handoff Git failure, for example a timeout or an old Git version | No worktree exists. The error gives the exit code and the first part of the Git error text. Fix Git, then call the tool again. |
201
207
  | Handoff cancellation | Before creation, nothing remains. After creation, reported resources remain; later launch or delivery steps stop. |
202
208
  | Handoff start or prompt failure | Resources remain. Errors identify worktree, branch, workspace, tab, pane, and agent. No automatic cleanup occurs. |
203
209
  | `agent_blocked` or `agent_prompt_stalled` | Prompt delivery failed. Inspect the agent before retrying. |
package/internal/btw.ts CHANGED
@@ -672,6 +672,10 @@ export async function registerBtwExtension(
672
672
  pane: paneId,
673
673
  args: agentStartArgs,
674
674
  options: { timeout: 45_000 },
675
+ // `pane split` returns the pane before its shell reads input. Wait for
676
+ // the shell, so the launch command cannot be typed into a busy tty and
677
+ // be lost.
678
+ freshPane: true,
675
679
  shouldRetry: (candidate) => !candidate.killed && launchGeneration === sessionGeneration,
676
680
  });
677
681
  } catch (error) {
@@ -1,6 +1,7 @@
1
+ import { realpath } from "node:fs/promises";
1
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
3
  import { createHerdrClient, herdrCommandFailure } from "@hcflabs/pi-herdr";
3
- import { resolveRepoTarget } from "@hcflabs/pi-repo";
4
+ import { discoverRepos, gitTopLevel, resolveRepoTarget, type RepoOptions } from "@hcflabs/pi-repo";
4
5
  import { Type } from "typebox";
5
6
  import {
6
7
  createWorktree,
@@ -13,6 +14,12 @@ import {
13
14
  } from "./worktree.ts";
14
15
 
15
16
  const PROMPT_TIMEOUT_MS = 30_000;
17
+ // An error message lists at most this many repo selectors, and searches for them for at most this long.
18
+ const MAX_SELECTORS = 20;
19
+ const SELECTOR_SEARCH_MS = 5_000;
20
+ const TEXT_LIMIT = 300;
21
+
22
+ const bounded = (text: string) => text.length > TEXT_LIMIT ? `${text.slice(0, TEXT_LIMIT)}...` : text;
16
23
 
17
24
  const nonEmpty = (description: string) => Type.String({ description, minLength: 1, pattern: "\\S" });
18
25
 
@@ -26,7 +33,7 @@ const HandoffParams = Type.Object({
26
33
  }),
27
34
  prompt: nonEmpty("Self-contained task prompt for the new agent"),
28
35
  repo: Type.Optional(nonEmpty(
29
- "Child Git repository for the worktree, as a path relative to the Pi working directory. Omit it to use the repository of the current Herdr workspace.",
36
+ "Git repository for the worktree, as a path relative to the Pi working directory. Use . for the working directory itself when it is a Git top-level directory. Omit it to use the repository of the current Herdr workspace, or the working directory when the workspace has no Git checkout and the working directory is a Git top-level directory.",
30
37
  )),
31
38
  });
32
39
 
@@ -42,7 +49,7 @@ export default function herdrHandoffExtension(pi: ExtensionAPI): void {
42
49
  promptSnippet: "Hand off a separate task to a new Pi agent in a new Herdr worktree from local main",
43
50
  promptGuidelines: [
44
51
  "Use herdr_handoff for a separate task that the user authorized, for example through /handoff-worktree. A handoff has no checked integration: the new agent works unsupervised.",
45
- "When the Pi working directory holds several repositories, set repo to the child repository of the task. herdr_handoff never selects a repository automatically.",
52
+ "When the Pi working directory is not a Git repository, or holds several repositories, set repo to the child repository of the task. herdr_handoff never selects a child repository automatically.",
46
53
  ],
47
54
  parameters: HandoffParams,
48
55
  executionMode: "sequential",
@@ -50,32 +57,60 @@ export default function herdrHandoffExtension(pi: ExtensionAPI): void {
50
57
  async execute(_toolCallId, { branch, label, agentName, prompt, repo }, signal, _onUpdate, ctx) {
51
58
  const paneId = requiredString(process.env.HERDR_PANE_ID, "HERDR_PANE_ID");
52
59
  const git = (cwd: string, args: string[]) => pi.exec("git", args, { cwd });
60
+ const repoOptions: RepoOptions = {
61
+ signal,
62
+ runProcess: (command, args, options) => pi.exec(command, args, { cwd: options.cwd, signal: options.signal, timeout: options.timeoutMs ?? undefined }),
63
+ };
64
+ /** List the repo values below the Pi working directory. A failed search adds no text. */
65
+ const selectorHint = async (): Promise<string> => {
66
+ try {
67
+ const found = await discoverRepos(ctx.cwd, { ...repoOptions, limit: MAX_SELECTORS, budgetMs: SELECTOR_SEARCH_MS });
68
+ if (found.repos.length === 0) return `Discovery found no Git repository below ${found.base}.`;
69
+ return `Repositories below ${found.base}: ${found.repos.map((item) => bounded(item.repo)).join(", ")}.${found.truncated ? " The list may be incomplete." : ""}`;
70
+ } catch {
71
+ return "";
72
+ }
73
+ };
74
+ const needRepo = async (reason: string) =>
75
+ new Error(`herdr_handoff: ${reason} Set the repo parameter to a Git repository, as a path relative to ${ctx.cwd}. ${await selectorHint()} Nothing was created.`);
76
+ const repository = async (cwd: string): Promise<string> => {
77
+ const result = await git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
78
+ if (result.code === 0 && !result.killed) return result.stdout.trim();
79
+ // Only a second check that finds no Git directory means "not a repository". Any other failure keeps its exit code.
80
+ const top = result.killed ? "failed" : await gitTopLevel(cwd, repoOptions).catch(() => "failed");
81
+ if (top === undefined) {
82
+ if (cwd === ctx.cwd) throw await needRepo(`${cwd} is not in a Git repository.`);
83
+ throw new Error(`herdr_handoff: ${cwd} is not in a Git repository; nothing was created.`);
84
+ }
85
+ const stderr = result.stderr.trim();
86
+ const outcome = result.killed ? `did not finish in ${cwd}` : `failed in ${cwd} with exit ${result.code}`;
87
+ throw new Error(`herdr_handoff: git rev-parse --git-common-dir ${outcome}${stderr ? `: ${bounded(stderr)}` : ""}. Nothing was created.`);
88
+ };
53
89
  let gitCwd: string;
54
90
  let location: string[];
55
91
  if (repo === undefined) {
56
92
  const workspace = await resolveWorkspace(herdr, ctx.cwd, paneId);
57
93
  if (!workspace.checkout) {
58
- throw new Error(
59
- `herdr_handoff: Herdr workspace ${workspace.workspaceId} has no Git checkout. Set repo to a child repository relative to ${ctx.cwd}; nothing was created.`,
60
- );
61
- }
62
- const repository = async (cwd: string) => {
63
- const result = await git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
64
- if (result.code !== 0 || result.killed) throw new Error(`herdr_handoff: ${cwd} is not in a Git repository; nothing was created.`);
65
- return result.stdout.trim();
66
- };
67
- // The worktree comes from the pane's workspace, so it must be the repository checked here.
68
- if (await repository(ctx.cwd) !== await repository(workspace.checkout)) {
69
- throw new Error(`herdr_handoff: ${ctx.cwd} and Herdr workspace ${workspace.workspaceId} (${workspace.checkout}) are different Git repositories; nothing was created.`);
94
+ // A plain workspace has no checkout to branch from. A working directory that is a Git top-level directory is the repository.
95
+ const top = await gitTopLevel(ctx.cwd, repoOptions).catch((error: unknown) => {
96
+ throw new Error(`herdr_handoff: ${errorMessage(error)} Nothing was created.`, { cause: error });
97
+ });
98
+ if (top === undefined || top !== await realpath(ctx.cwd)) {
99
+ throw await needRepo(`Herdr workspace ${workspace.workspaceId} has no Git checkout, and ${ctx.cwd} is not a Git top-level directory${top === undefined ? "" : ` (Git reports ${top})`}.`);
100
+ }
101
+ gitCwd = top;
102
+ location = ["--cwd", top];
103
+ } else {
104
+ // The worktree comes from the pane's workspace, so it must be the repository checked here.
105
+ if (await repository(ctx.cwd) !== await repository(workspace.checkout)) {
106
+ throw new Error(`herdr_handoff: ${ctx.cwd} and Herdr workspace ${workspace.workspaceId} (${workspace.checkout}) are different Git repositories; nothing was created.`);
107
+ }
108
+ gitCwd = ctx.cwd;
109
+ location = ["--workspace", await worktreeParentWorkspace(herdr, ctx.cwd, workspace)];
70
110
  }
71
- gitCwd = ctx.cwd;
72
- location = ["--workspace", await worktreeParentWorkspace(herdr, ctx.cwd, workspace)];
73
111
  } else {
74
112
  // Herdr opens or creates the repository's primary workspace when it gets --cwd.
75
- const target = await resolveRepoTarget(ctx.cwd, repo, {
76
- signal,
77
- runProcess: (command, args, options) => pi.exec(command, args, { cwd: options.cwd, signal: options.signal, timeout: options.timeoutMs ?? undefined }),
78
- }).catch((error: unknown) => {
113
+ const target = await resolveRepoTarget(ctx.cwd, repo, repoOptions).catch((error: unknown) => {
79
114
  throw new Error(`herdr_handoff: ${errorMessage(error)} Nothing was created.`, { cause: error });
80
115
  });
81
116
  gitCwd = target.root;
package/internal/recap.ts CHANGED
@@ -91,7 +91,7 @@ export default function idleRecapExtension(pi: ExtensionAPI): void {
91
91
 
92
92
  const recap = async (ctx: ExtensionContext) => {
93
93
  timer = undefined;
94
- const leaf = ctx.sessionManager.getLeafId();
94
+ const leaf = conversationLeaf(ctx.sessionManager);
95
95
  if (leaf === recappedLeaf || !idle(ctx)) return;
96
96
  const messages = buildSessionContext(ctx.sessionManager.getEntries(), leaf).messages;
97
97
  // buildMergeTranscript keeps only user and assistant turns; summaries carry the goal after compaction or branch navigation.
@@ -111,7 +111,7 @@ export default function idleRecapExtension(pi: ExtensionAPI): void {
111
111
  active = controller;
112
112
  try {
113
113
  const text = await generateRecap(prompt, ctx, controller.signal, reportTaskModels);
114
- if (active !== controller || !idle(ctx) || ctx.sessionManager.getLeafId() !== leaf) return;
114
+ if (active !== controller || !idle(ctx) || conversationLeaf(ctx.sessionManager) !== leaf) return;
115
115
  recappedLeaf = leaf;
116
116
  if (ctx.mode === "tui") {
117
117
  ctx.ui.setWidget(WIDGET_KEY, (_tui, theme) => ({
@@ -157,3 +157,10 @@ export default function idleRecapExtension(pi: ExtensionAPI): void {
157
157
  pi.on("session_tree", (_event, ctx) => cancel(ctx));
158
158
  pi.on("session_shutdown", (_event, ctx) => cancel(ctx));
159
159
  }
160
+
161
+ /** Leaf ID without trailing usage entries. Pi appends a usage entry for each cache warm. */
162
+ function conversationLeaf(sessionManager: ExtensionContext["sessionManager"]): string | null {
163
+ let entry = sessionManager.getLeafEntry();
164
+ while (entry?.type === "usage") entry = entry.parentId ? sessionManager.getEntry(entry.parentId) : undefined;
165
+ return entry?.id ?? null;
166
+ }
@@ -227,6 +227,12 @@ export async function launchPiAgent(
227
227
  pane,
228
228
  args: input.args,
229
229
  options: { cwd },
230
+ // Every caller passes a pane it just created: a new tab, a worktree root
231
+ // pane, or an extra tab. Herdr returns those IDs before the pane shell
232
+ // reads input, and shell startup files can still own the foreground. Wait
233
+ // for the shell, so the launch command cannot be typed into a busy tty and
234
+ // be lost.
235
+ freshPane: true,
230
236
  onPaneBusy: input.onPaneBusy
231
237
  ? async () => (pane = await input.onPaneBusy!())
232
238
  : undefined,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hcflabs/pi-herdr-tools",
3
- "version": "1.9.0",
3
+ "version": "1.10.1",
4
4
  "description": "Clone, hand off, name, and finish Pi conversations in Herdr, with mergeable side questions.",
5
5
  "keywords": ["pi-package", "pi", "herdr", "session", "clone", "side-thread", "title"],
6
6
  "type": "module",
@@ -13,9 +13,9 @@
13
13
  "pack:check": "npm pack --dry-run"
14
14
  },
15
15
  "peerDependencies": {
16
- "@earendil-works/pi-agent-core": "^1.3.0",
17
- "@earendil-works/pi-coding-agent": "^1.3.0",
18
- "@earendil-works/pi-tui": "^1.3.0",
16
+ "@earendil-works/pi-agent-core": "^1.6.0",
17
+ "@earendil-works/pi-coding-agent": "^1.6.0",
18
+ "@earendil-works/pi-tui": "^1.6.0",
19
19
  "typebox": "^1.3.15"
20
20
  },
21
21
  "dependencies": {
@@ -26,9 +26,9 @@
26
26
  "@hcflabs/pi-task-models": "^9.0.0"
27
27
  },
28
28
  "devDependencies": {
29
- "@earendil-works/pi-agent-core": "1.3.0",
30
- "@earendil-works/pi-coding-agent": "1.3.0",
31
- "@earendil-works/pi-tui": "1.3.0"
29
+ "@earendil-works/pi-agent-core": "1.6.0",
30
+ "@earendil-works/pi-coding-agent": "1.6.0",
31
+ "@earendil-works/pi-tui": "1.6.0"
32
32
  },
33
33
  "repository": {
34
34
  "type": "git",
@@ -9,5 +9,5 @@ If the issue is empty, stop and ask the user to run `/handoff-worktree <issue>`.
9
9
 
10
10
  1. Gather only the missing facts from the conversation and the repository. Ask one focused question only if the repository, expected outcome, or a critical constraint is unclear.
11
11
  2. Write one self-contained prompt: problem, evidence, expected outcome, constraints, starting files, validation, and requested delivery. Exclude unrelated context, secrets, and stale runtime IDs.
12
- 3. Choose a concise branch, a short label, and a unique agent name. If the Pi working directory holds several repositories, also choose `repo`: the path of the child repository, relative to the working directory.
12
+ 3. Choose a concise branch, a short label, and a unique agent name. If the Pi working directory is not a Git repository, or holds several repositories, also choose `repo`: the path of the child repository, relative to the working directory. If `herdr_handoff` reports that `repo` is required, choose from the repositories that it lists.
13
13
  4. Call `herdr_handoff` with them. Report its result. Do not wait for the new agent to finish.