@hcflabs/pi-herdr-tools 0.0.0-stage → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,243 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { herdrCommandFailure, startPiAgent, type HerdrClient, type HerdrExecResult } from "@hcflabs/pi-herdr";
3
+
4
+ type Herdr = HerdrClient<{ cwd: string }>;
5
+
6
+ type WorkspaceInfo = {
7
+ workspace_id?: unknown;
8
+ worktree?: {
9
+ checkout_path?: unknown;
10
+ repo_root?: unknown;
11
+ is_linked_worktree?: unknown;
12
+ } | null;
13
+ };
14
+
15
+ export type HerdrWorkspace = {
16
+ workspaceId: string;
17
+ checkout: string | undefined;
18
+ repoRoot: string | undefined;
19
+ isLinkedWorktree: boolean;
20
+ };
21
+
22
+ type CreatedWorktree = {
23
+ workspaceId: string;
24
+ tabId: string;
25
+ rootPaneId: string;
26
+ checkoutPath: string;
27
+ };
28
+
29
+ type LaunchTarget = { tabId: string; paneId: string };
30
+
31
+ export const errorMessage = (error: unknown) => error instanceof Error ? error.message : String(error);
32
+
33
+ export function requiredString(value: unknown, label: string): string {
34
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${label} is missing.`);
35
+ return value;
36
+ }
37
+
38
+ /** Resolve the Herdr workspace that owns `paneId`, with its Git worktree identity. */
39
+ export async function resolveWorkspace(herdr: Herdr, cwd: string, paneId: string): Promise<HerdrWorkspace> {
40
+ const paneResponse = await herdr.json(["pane", "get", paneId], { cwd });
41
+ const pane = (paneResponse as { result?: { pane?: { workspace_id?: unknown } } }).result?.pane;
42
+ const workspaceId = requiredString(pane?.workspace_id, "Herdr pane response workspace_id");
43
+ const workspaceResponse = await herdr.json(["workspace", "get", workspaceId], { cwd });
44
+ const workspace = (workspaceResponse as { result?: { workspace?: WorkspaceInfo } }).result?.workspace;
45
+ if (requiredString(workspace?.workspace_id, "Herdr workspace response workspace_id") !== workspaceId) {
46
+ throw new Error(`Herdr workspace response did not match ${workspaceId}.`);
47
+ }
48
+ const checkout = workspace?.worktree == null
49
+ ? undefined
50
+ : requiredString(workspace.worktree.checkout_path, "Herdr workspace response checkout_path");
51
+ const repoRoot = typeof workspace?.worktree?.repo_root === "string" && workspace.worktree.repo_root.trim()
52
+ ? workspace.worktree.repo_root
53
+ : undefined;
54
+ const isLinkedWorktree = workspace?.worktree?.is_linked_worktree === true;
55
+ if (isLinkedWorktree && !repoRoot) {
56
+ throw new Error("Herdr workspace response is missing worktree.repo_root for a linked worktree.");
57
+ }
58
+ return { workspaceId, checkout, repoRoot, isLinkedWorktree };
59
+ }
60
+
61
+ /**
62
+ * Herdr only creates worktrees from the repo parent workspace; a linked
63
+ * worktree must retarget the parent.
64
+ */
65
+ export async function worktreeParentWorkspace(herdr: Herdr, cwd: string, workspace: HerdrWorkspace): Promise<string> {
66
+ if (!workspace.isLinkedWorktree) return workspace.workspaceId;
67
+ const listing = await herdr.json(["workspace", "list"], { cwd });
68
+ const result = (listing as { result?: { workspaces?: WorkspaceInfo[] } }).result;
69
+ const parent = (Array.isArray(result?.workspaces) ? result.workspaces : []).find((entry) =>
70
+ entry.worktree != null && !entry.worktree.is_linked_worktree &&
71
+ entry.worktree.checkout_path === workspace.repoRoot);
72
+ return typeof parent?.workspace_id === "string"
73
+ ? parent.workspace_id
74
+ : requiredString(undefined, `Repo parent workspace for ${workspace.repoRoot} in herdr workspace list`);
75
+ }
76
+
77
+ /**
78
+ * Run `herdr worktree create` and parse its response. A killed or incomplete
79
+ * create is ambiguous: Herdr may have retained partial worktree state, so the
80
+ * error names every returned identifier. `action` prefixes that error.
81
+ */
82
+ export async function createWorktree(
83
+ herdr: Herdr,
84
+ cwd: string,
85
+ args: readonly string[],
86
+ action: string,
87
+ ): Promise<CreatedWorktree> {
88
+ const createdWorktree = await herdr.exec(args, { cwd });
89
+ if (createdWorktree.code !== 0 && !createdWorktree.killed) {
90
+ throw new Error(herdrCommandFailure(args, createdWorktree));
91
+ }
92
+
93
+ let workspaceId: string | undefined;
94
+ let tabId: string | undefined;
95
+ let rootPaneId: string | undefined;
96
+ let checkoutPath: string | undefined;
97
+ try {
98
+ const response: unknown = JSON.parse(createdWorktree.stdout);
99
+ if (!response || typeof response !== "object" || Array.isArray(response)) {
100
+ throw new Error("Herdr worktree create returned invalid JSON");
101
+ }
102
+ // Herdr nests checkout_path under workspace.worktree; the top-level
103
+ // result.worktree uses `path` instead.
104
+ const result = (response as {
105
+ result?: {
106
+ workspace?: { workspace_id?: unknown; worktree?: { checkout_path?: unknown } };
107
+ tab?: { tab_id?: unknown };
108
+ root_pane?: { pane_id?: unknown };
109
+ };
110
+ }).result;
111
+ // Collect every returned identifier before validating so recovery
112
+ // keeps all known IDs even when an earlier field is missing.
113
+ workspaceId = typeof result?.workspace?.workspace_id === "string" ? result.workspace.workspace_id : undefined;
114
+ tabId = typeof result?.tab?.tab_id === "string" ? result.tab.tab_id : undefined;
115
+ rootPaneId = typeof result?.root_pane?.pane_id === "string" ? result.root_pane.pane_id : undefined;
116
+ checkoutPath = typeof result?.workspace?.worktree?.checkout_path === "string" && result.workspace.worktree.checkout_path.trim()
117
+ ? result.workspace.worktree.checkout_path
118
+ : undefined;
119
+ if (createdWorktree.killed) {
120
+ throw new Error("Herdr worktree create was killed before completion.");
121
+ }
122
+ const missing = [
123
+ [workspaceId, "workspace_id"],
124
+ [tabId, "tab_id"],
125
+ [rootPaneId, "root_pane.pane_id"],
126
+ [checkoutPath, "workspace.worktree.checkout_path"],
127
+ ].filter(([value]) => !value).map(([, label]) => label);
128
+ if (missing.length > 0) {
129
+ throw new Error(`Herdr worktree create response is missing ${missing.join(", ")}.`);
130
+ }
131
+ } catch (error) {
132
+ const known = [
133
+ workspaceId && `workspace ${workspaceId}`,
134
+ tabId && `tab ${tabId}`,
135
+ rootPaneId && `root pane ${rootPaneId}`,
136
+ checkoutPath && `checkout ${checkoutPath}`,
137
+ ].filter(Boolean).join(", ");
138
+ throw new Error(
139
+ `${action} could not be confirmed after creating a Herdr worktree${known ? ` (${known})` : ""}; Herdr may have retained a partial worktree workspace, inspect herdr workspace list: ${errorMessage(error)}`,
140
+ { cause: error },
141
+ );
142
+ }
143
+ return { workspaceId: workspaceId!, tabId: tabId!, rootPaneId: rootPaneId!, checkoutPath: checkoutPath! };
144
+ }
145
+
146
+ export function parseCreatedTab(createdTab: HerdrExecResult, workspaceId: string): { tabId: string; rootPaneId: string } {
147
+ let tabId: string | undefined;
148
+ let rootPaneId: string | undefined;
149
+ try {
150
+ const response: unknown = JSON.parse(createdTab.stdout);
151
+ if (!response || typeof response !== "object" || Array.isArray(response)) {
152
+ throw new Error("Herdr tab create returned invalid JSON");
153
+ }
154
+ const result = (response as { result?: { tab?: { tab_id?: unknown }; root_pane?: { pane_id?: unknown } } }).result;
155
+ tabId = typeof result?.tab?.tab_id === "string" && result.tab.tab_id.trim() ? result.tab.tab_id : undefined;
156
+ rootPaneId = typeof result?.root_pane?.pane_id === "string" && result.root_pane.pane_id.trim()
157
+ ? result.root_pane.pane_id
158
+ : undefined;
159
+ const missing = [!tabId && "tab_id", !rootPaneId && "root_pane.pane_id"].filter(Boolean).join(", ");
160
+ if (missing) throw new Error(`Herdr tab create response is missing ${missing}.`);
161
+ return { tabId: tabId!, rootPaneId: rootPaneId! };
162
+ } catch (error) {
163
+ const retained = [`workspace ${workspaceId}`, tabId && `tab ${tabId}`, rootPaneId && `root pane ${rootPaneId}`]
164
+ .filter(Boolean).join(", ");
165
+ throw new Error(`Herdr tab create response could not be parsed; retained ${retained}: ${errorMessage(error)}`, { cause: error });
166
+ }
167
+ }
168
+
169
+ // A worktree layout plugin (e.g. herdr-plus) can start its own agent in a new
170
+ // worktree's root pane right after creation. Give it a moment to appear so the
171
+ // new agent can move to its own tab instead of failing with agent_pane_busy.
172
+ async function waitForRootPaneAgent(herdr: Herdr, cwd: string, paneId: string): Promise<string | undefined> {
173
+ for (let attempt = 0; attempt < 12; attempt += 1) {
174
+ const response = await herdr.json(["pane", "get", paneId], { cwd });
175
+ const agent = (response as { result?: { pane?: { agent?: unknown } } }).result?.pane?.agent;
176
+ if (typeof agent === "string" && agent.trim()) return agent;
177
+ await delay(250);
178
+ }
179
+ return undefined;
180
+ }
181
+
182
+ /**
183
+ * Choose the pane for a new agent in a created worktree. A layout plugin may
184
+ * claim the root pane; park the agent in its own tab so both coexist. The
185
+ * returned target updates in place when `onPaneBusy` creates that tab later.
186
+ */
187
+ export async function prepareWorktreeLaunch(
188
+ herdr: Herdr,
189
+ cwd: string,
190
+ worktree: CreatedWorktree,
191
+ ): Promise<{ target: LaunchTarget; onPaneBusy?: () => Promise<string> }> {
192
+ const target: LaunchTarget = { tabId: worktree.tabId, paneId: worktree.rootPaneId };
193
+ const createTab = async (): Promise<string> => {
194
+ const tabArgs = ["tab", "create", "--workspace", worktree.workspaceId, "--cwd", worktree.checkoutPath, "--no-focus"] as const;
195
+ const createdTab = await herdr.exec(tabArgs, { cwd });
196
+ if (createdTab.code !== 0 || createdTab.killed) {
197
+ throw new Error(herdrCommandFailure(tabArgs, createdTab));
198
+ }
199
+ ({ tabId: target.tabId, rootPaneId: target.paneId } = parseCreatedTab(createdTab, worktree.workspaceId));
200
+ return target.paneId;
201
+ };
202
+ if (await waitForRootPaneAgent(herdr, cwd, worktree.rootPaneId)) await createTab();
203
+ return { target, onPaneBusy: target.paneId === worktree.rootPaneId ? createTab : undefined };
204
+ }
205
+
206
+ /**
207
+ * Start a Pi agent and wrap every failure as an ambiguous launch that names the
208
+ * retained resources. `retained` is read at failure time so a busy-pane move
209
+ * reports the final target.
210
+ */
211
+ export async function launchPiAgent(
212
+ herdr: Herdr,
213
+ cwd: string,
214
+ input: {
215
+ action: string;
216
+ name: string;
217
+ pane: string;
218
+ args: readonly string[];
219
+ retained: () => string;
220
+ onPaneBusy?: () => Promise<string>;
221
+ },
222
+ ): Promise<void> {
223
+ let pane = input.pane;
224
+ try {
225
+ const result = await startPiAgent(herdr, {
226
+ name: input.name,
227
+ pane,
228
+ args: input.args,
229
+ options: { cwd },
230
+ onPaneBusy: input.onPaneBusy
231
+ ? async () => (pane = await input.onPaneBusy!())
232
+ : undefined,
233
+ });
234
+ if (result.code === 0 && !result.killed) return;
235
+ const startArgs = ["agent", "start", input.name, "--kind", "pi", "--pane", pane, "--", ...input.args];
236
+ throw new Error(herdrCommandFailure(startArgs, result));
237
+ } catch (error) {
238
+ throw new Error(
239
+ `${input.action} launch could not be confirmed after starting agent ${input.name}; retained ${input.retained()}: ${errorMessage(error)}`,
240
+ { cause: error },
241
+ );
242
+ }
243
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@hcflabs/pi-herdr-tools",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.7.0",
4
+ "description": "Clone, hand off, name, and finish Pi conversations in Herdr, with mergeable side questions.",
5
+ "keywords": ["pi-package", "pi", "herdr", "session", "clone", "side-thread", "title"],
6
+ "type": "module",
7
+ "engines": { "node": ">=22.19.0" },
8
+ "license": "MIT",
9
+ "files": ["LICENSE", "extensions", "internal", "prompts", "docs", "README.md"],
10
+ "scripts": {
11
+ "test": "node --test test/*.test.ts",
12
+ "typecheck": "tsc --noEmit --allowImportingTsExtensions --target ES2022 --module NodeNext --moduleResolution NodeNext --skipLibCheck extensions/*.ts internal/*.ts test/*.test.ts",
13
+ "pack:check": "npm pack --dry-run"
14
+ },
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",
19
+ "typebox": "^1.3.15"
20
+ },
21
+ "dependencies": {
22
+ "@hcflabs/pi-config-store": "^4.0.0",
23
+ "@hcflabs/pi-herdr": "^0.5.0",
24
+ "@hcflabs/pi-repo": "^0.1.0",
25
+ "@hcflabs/pi-task-models": "^9.0.0"
26
+ },
27
+ "devDependencies": {
28
+ "@earendil-works/pi-agent-core": "1.3.0",
29
+ "@earendil-works/pi-coding-agent": "1.3.0",
30
+ "@earendil-works/pi-tui": "1.3.0"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/hcflabs/pi-harness.git",
35
+ "directory": "extensions/pi-herdr-tools"
36
+ },
37
+ "bugs": { "url": "https://github.com/hcflabs/pi-harness/issues" },
38
+ "publishConfig": { "access": "public" },
39
+ "pi": { "extensions": ["./extensions/index.ts"], "prompts": ["./prompts"] }
40
+ }
@@ -0,0 +1,13 @@
1
+ ---
2
+ description: Hand off a separate issue to a new Herdr worktree from main.
3
+ argument-hint: "<issue>"
4
+ ---
5
+
6
+ Hand off this separate issue to a new Herdr worktree: $ARGUMENTS
7
+
8
+ If the issue is empty, stop and ask the user to run `/handoff-worktree <issue>`. Do not modify the current worktree.
9
+
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
+ 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.
13
+ 4. Call `herdr_handoff` with them. Report its result. Do not wait for the new agent to finish.