@henryqw/pi-subagent 27.14.2 → 27.14.3

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
@@ -142,7 +142,7 @@ Staging, validation, and promotion require clean, unchanged Main. After a defini
142
142
 
143
143
  ### Inspect work
144
144
 
145
- Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows are grouped under **Direct**, **Isolated**, and **Orphaned · parent checkout removed**. Before the menu opens, and after each **Refresh**, a **Current subagent work** report shows which subagents are working. Without interactive UI, `/subagent` sends the report and the request list, including history.
145
+ Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows are grouped under **Direct**, **Isolated**, and **Orphaned · parent checkout removed**. Before the menu opens, and after each **Refresh**, a **Current subagent work** report shows which subagents are working. Without interactive UI, `/subagent` sends the report and the request list, including history. In the terminal, the menu replaces the editor and uses at most half the terminal height. It does not overlay the report or the transcript.
146
146
 
147
147
  Each row starts with a status symbol: `●` active, `✓` completed, `⚠` needs attention, `✗` failed. Terminal requests stay hidden until you select **Completed / history**; this filter deletes no records. `/subagent` reports show as transcript entries that the model does not get.
148
148
 
@@ -226,6 +226,8 @@ Role extensions and MCP servers are trusted executable code, not a sandbox. Sele
226
226
 
227
227
  For uncertain direct termination, open `/subagent`, select the exact workflow, and choose **Close/cancel-and-release ALL owned workers in this workflow**. This stops all owned workers, not only the selected one. Resolve reported blockers and repeat the action. Recorded-only tasks cannot release admission. Restarting Pi does not prove termination. Inspect partial changes before new writes; never blindly repeat commits or delete work.
228
228
 
229
+ After Close/cancel-and-release proves pane absence, it terminates the processes that hold the exact private process lease of an owned worker (`SIGTERM`, then `SIGKILL`). Automatic completion, continuation, and Subagent Collection never send signals.
230
+
229
231
  Unverified tab allocations retain evidence but offer no Close action. Reconcile them manually against Herdr; do not recreate tabs, guess IDs, or restart to bypass admission. See [Direct contract](./docs/orchestration.md#direct-contract).
230
232
 
231
233
  After coordinator interruption, restart Pi and run `/subagent recover` in the canonical repository. Use `subagent_status` for exact evidence; never take over a live productive lease or replay uncertain prompts, merges, or promotion. For aborted requests with retained resources, resolve blockers and repeat `subagent_abort`. See [Recover after interruption](./docs/orchestration.md#recover-after-interruption) and [Recovery and state](./docs/orchestration.md#recovery-and-state).
@@ -59,13 +59,15 @@ export declare class DirectAllocationError extends Error {
59
59
  readonly allocation: DirectAllocation;
60
60
  constructor(allocation: DirectAllocation, cause: unknown);
61
61
  }
62
- export declare function createDirectHerdr(pi: Pick<ExtensionAPI, "exec">, cwd: string, idleMs: number): {
62
+ export declare function createDirectHerdr(pi: Pick<ExtensionAPI, "exec">, cwd: string, idleMs: number, kill?: (pid: number, signal: NodeJS.Signals) => void): {
63
63
  workspaceId: string;
64
64
  cwd: string;
65
65
  /** Close only an exact owned pane, then prove it and its leased children stopped.
66
66
  * A task result or Ctrl-C acknowledgement is not termination evidence.
67
- * `settledOnly` refuses to close a listed agent that is not idle or done. */
68
- stop(tab: Pick<DirectTab, "name" | "tabId" | "paneId" | "leasePath">, current?: () => boolean, settledOnly?: boolean): Promise<void>;
67
+ * `settled` refuses to close a listed agent that is not idle or done. Only an explicit
68
+ * user stop or Close uses `terminate`: after pane absence it signals each holder that a
69
+ * per-PID scan still proves holds the exact lease. Other callers only prove. */
70
+ stop(tab: Pick<DirectTab, "name" | "tabId" | "paneId" | "leasePath">, current?: () => boolean, mode?: "proof" | "settled" | "terminate"): Promise<void>;
69
71
  /** Collection preserves the saved conversation and private lease for continuation and recovery. */
70
72
  collect(tab: DirectTab, current: () => boolean): Promise<boolean>;
71
73
  /** `resume` reuses a stopped worker's saved session and private lease instead of a new temp directory. */
@@ -278,7 +278,7 @@ export class DirectAllocationError extends Error {
278
278
  this.allocation = allocation;
279
279
  }
280
280
  }
281
- export function createDirectHerdr(pi, cwd, idleMs) {
281
+ export function createDirectHerdr(pi, cwd, idleMs, kill = (pid, signal) => process.kill(pid, signal)) {
282
282
  if (process.env.HERDR_ENV !== "1")
283
283
  throw new Error("Direct delegation requires a Herdr-managed Pi pane (HERDR_ENV=1).");
284
284
  const workspaceId = field(process.env.HERDR_WORKSPACE_ID, "HERDR_WORKSPACE_ID");
@@ -299,8 +299,10 @@ export function createDirectHerdr(pi, cwd, idleMs) {
299
299
  cwd: workingDir,
300
300
  /** Close only an exact owned pane, then prove it and its leased children stopped.
301
301
  * A task result or Ctrl-C acknowledgement is not termination evidence.
302
- * `settledOnly` refuses to close a listed agent that is not idle or done. */
303
- async stop(tab, current = () => true, settledOnly = false) {
302
+ * `settled` refuses to close a listed agent that is not idle or done. Only an explicit
303
+ * user stop or Close uses `terminate`: after pane absence it signals each holder that a
304
+ * per-PID scan still proves holds the exact lease. Other callers only prove. */
305
+ async stop(tab, current = () => true, mode = "proof") {
304
306
  const requireCurrent = () => { if (!current())
305
307
  throw new Error("Direct task scope changed; reopen /subagent."); };
306
308
  requireCurrent();
@@ -333,7 +335,7 @@ export function createDirectHerdr(pi, cwd, idleMs) {
333
335
  || agent.tab_id !== tab.tabId || agent.workspace_id !== workspaceId || agent.cwd !== workingDir
334
336
  || tab.paneId === callerPane)
335
337
  throw new Error("Worker termination requires one exact owned agent, workspace, checkout, tab and pane match.");
336
- if (settledOnly && agent.agent_status !== "idle" && agent.agent_status !== "done") {
338
+ if (mode === "settled" && agent.agent_status !== "idle" && agent.agent_status !== "done") {
337
339
  throw new Error(`Herdr agent ${tab.name} is ${String(agent.agent_status)}, not idle or done; it was not closed`);
338
340
  }
339
341
  requireCurrent();
@@ -342,13 +344,36 @@ export function createDirectHerdr(pi, cwd, idleMs) {
342
344
  if ((await panes()).some((pane) => pane.pane_id === tab.paneId || pane.tab_id === tab.tabId)) {
343
345
  throw new Error(`Owned pane ${tab.paneId} is still present; termination is unproved.`);
344
346
  }
345
- for (let scan = 0; scan < 2; scan++) {
346
- const holders = await scanProcessLease(tab.leasePath, (args) => pi.exec("lsof", args, { cwd: workingDir, timeout: 3_000 }));
347
+ const scan = (pid) => scanProcessLease(tab.leasePath, (args) => pi.exec("lsof", args, { cwd: workingDir, timeout: 3_000 }), pid);
348
+ let holders = await scan();
349
+ if (mode === "terminate") {
350
+ for (const [signal, wait] of [["SIGTERM", 250], ["SIGKILL", 100]]) {
351
+ if (!holders.length)
352
+ break;
353
+ for (const pid of holders) {
354
+ requireCurrent();
355
+ if (!(await scan(pid)).includes(pid))
356
+ continue;
357
+ requireCurrent();
358
+ try {
359
+ kill(pid, signal);
360
+ }
361
+ catch (error) {
362
+ if (error.code !== "ESRCH")
363
+ throw error;
364
+ }
365
+ }
366
+ await sleep(wait);
367
+ holders = await scan();
368
+ }
347
369
  if (holders.length)
348
- throw new Error(`Owned process lease ${tab.leasePath} still has holders: ${holders.join(", ")}. Stop those owned processes, then retry Close/cancel-and-release.`);
349
- if (scan === 0)
350
- await sleep(50);
370
+ throw new Error(`Owned process lease ${tab.leasePath} still has holders after SIGTERM and SIGKILL: ${holders.join(", ")}. Inspect those processes before retrying Close/cancel-and-release.`);
351
371
  }
372
+ if (holders.length)
373
+ throw new Error(`Owned process lease ${tab.leasePath} still has holders: ${holders.join(", ")}. Stop those owned processes, or use /subagent Stop or Close/cancel-and-release of the owning workflow to terminate them.`);
374
+ await sleep(50);
375
+ if ((await scan()).length)
376
+ throw new Error(`Owned process lease ${tab.leasePath} did not remain empty for two consecutive scans.`);
352
377
  requireCurrent();
353
378
  },
354
379
  /** Collection preserves the saved conversation and private lease for continuation and recovery. */
@@ -365,7 +390,7 @@ export function createDirectHerdr(pi, cwd, idleMs) {
365
390
  throw new Error("Direct collection tab identity or pane count changed.");
366
391
  }
367
392
  await assertSettledDirectSession(tab.sessionFile, tab.turn);
368
- await this.stop(tab, current, true);
393
+ await this.stop(tab, current, "settled");
369
394
  const response = await herdr.exec(["tab", "get", tab.tabId], options());
370
395
  if (!response.killed && hasHerdrErrorCode(response, "tab_not_found"))
371
396
  return true;
@@ -97,11 +97,11 @@ A write request runs its tasks in sequence. It holds checkout admission after th
97
97
 
98
98
  A failure in a write request stops further dispatch, but a worker with an uncertain state can still run. Chains replace each literal `{previous}` with the preceding successful answer and stop on failure. Task outcome and worker termination are separate.
99
99
 
100
- After settlement, the coordinator closes exact owned writer panes. It releases admission only after pane absence and two empty private process-lease scans. This proof requires native `lsof`. The coordinator removes no Git files, commits, or saved sessions. A failure stays a failure even when the coordinator releases admission.
100
+ After settlement, the coordinator closes exact owned writer panes. It releases admission only after pane absence and two empty private process-lease scans. This proof requires native `lsof`. This automatic step sends no signals, so a background process that the worker started and that holds its lease keeps admission held. The coordinator removes no Git files, commits, or saved sessions. A failure stays a failure even when the coordinator releases admission.
101
101
 
102
102
  Admission stays held if the close fails, identity changes, a leased child survives, or inspection is uncertain. In that case, open `/subagent`. Select the exact direct workflow. Then choose **Close/cancel-and-release ALL owned workers in this workflow** to cancel dispatch and try termination again. This action stops every owned worker of that workflow, not one selected worker.
103
103
 
104
- The action checks session, branch, epoch, and live ownership. Recorded-only tasks cannot unlock anything. Resolve the reported blocker, including any surviving owned process. Then do the same action again. A restart of Pi is not termination proof.
104
+ The action checks session, branch, epoch, and live ownership. Recorded-only tasks cannot unlock anything. After it proves pane absence, it sends `SIGTERM` to each process that holds the exact private lease of an owned worker. Then it sends `SIGKILL` to each process that survives. Before each signal, it scans the lease again for that PID, and it does not signal a PID that no longer holds the lease. If a holder survives, a scan fails, or ownership changes, admission stays held. Resolve the reported blocker, then do the same action again. A restart of Pi is not termination proof.
105
105
 
106
106
  Inspect partial changes before new writes. To recover, never retry a commit or delete work without inspection.
107
107
 
@@ -127,11 +127,11 @@ Before launch, the request fails if the reference is unknown or matches more tha
127
127
 
128
128
  If Herdr still lists the old agent, the agent must match the recorded name, pane, tab, workspace, and checkout. It must also be idle or done. The extension never closes a working or blocked agent. The extension closes the old pane, then proves pane absence and two empty lease scans.
129
129
 
130
- An absent old agent still requires two empty lease scans.
130
+ An absent old agent still requires two empty lease scans. Continuation and Subagent Collection never send signals to lease holders.
131
131
 
132
132
  Records saved before 27.0.0 have no turn identity. The extension cannot continue them. For these records, start a new task.
133
133
 
134
- In a running workflow that has only `read` tasks, `/subagent` shows **Stop this worker** for each running worker. It aborts only that worker, sends Ctrl-C, closes its exact pane, and proves pane absence and two empty lease scans. The result of the worker becomes a failure, `Stopped by user from /subagent`, and keeps any partial output. Other workers continue, but a chain stops its later steps.
134
+ In a running workflow that has only `read` tasks, `/subagent` shows **Stop this worker** for each running worker. It aborts only that worker, sends Ctrl-C, closes its exact pane, and proves pane absence. Then it terminates the remaining lease holders of that worker as Close does, and proves two empty lease scans. The result of the worker becomes a failure, `Stopped by user from /subagent`, and keeps any partial output. Other workers continue, but a chain stops its later steps.
135
135
 
136
136
  If the extension cannot prove termination of the stopped worker, the workflow keeps local ownership. So **Close/cancel-and-release** stays available. Main receives one result when the workflow finishes. A workflow with a `write` task offers only **Close/cancel-and-release ALL owned workers in this workflow**. Both actions check session, branch, and epoch, so a stale dialog cannot act.
137
137
 
@@ -344,9 +344,11 @@ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly C
344
344
  }
345
345
  return ctx.ui.custom<T | undefined>((tui, theme, _keys, done) => {
346
346
  const rows = labels.map((label, index) => ({ label, value: String(index) }));
347
+ // The menu replaces the editor, not the screen; cap its height to leave room for other content.
348
+ const menuHeight = () => Math.max(1, Math.floor(tui.terminal.rows / 2));
347
349
  const createList = () => {
348
- // Reserve title, key hints, and the native scroll indicator. Very short terminals show only the list.
349
- const height = tui.terminal.rows;
350
+ // Reserve title, key hints, and the native scroll indicator. Very short menus show only the list.
351
+ const height = menuHeight();
350
352
  const list = new SelectList(rows, Math.max(1, height - (height >= 4 ? 3 : 1)), getSelectListTheme());
351
353
  list.setSelectedIndex(selectedIndex);
352
354
  list.onSelectionChange = ({ value }) => { selectedIndex = Number(value); };
@@ -359,7 +361,7 @@ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly C
359
361
  render(width) {
360
362
  list = createList();
361
363
  const lines = list.render(width);
362
- if (tui.terminal.rows < 4) return lines.slice(0, tui.terminal.rows);
364
+ if (menuHeight() < 4) return lines.slice(0, menuHeight());
363
365
  return [truncateToWidth(theme.fg("accent", title), width), ...lines,
364
366
  truncateToWidth([`${keyText("tui.select.up")}/${keyText("tui.select.down")} scroll`,
365
367
  keyHint("tui.select.confirm", "select"), keyHint("tui.select.cancel", "cancel")].join(" · "), width)];
@@ -367,7 +369,7 @@ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly C
367
369
  handleInput(data) { list.handleInput(data); tui.requestRender(); },
368
370
  invalidate() { list.invalidate(); },
369
371
  };
370
- }, { overlay: true, overlayOptions: { width: "100%", maxHeight: "100%", margin: 0 } });
372
+ });
371
373
  }
372
374
 
373
375
  /** Multi-select on single-choice menus: each pick toggles one row until Continue. Returns chosen values in
@@ -259,7 +259,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
259
259
  const directTasks = new Map<string, {
260
260
  controller: AbortController; settled: Promise<void>; handles: DirectHandle[]; tabs: DirectTabRecord[];
261
261
  pendingResult?: (sessionId: string) => boolean;
262
- close?: (current: () => boolean) => Promise<void>; closeScope?: () => boolean; allocation?: DirectAllocationRecord; recovery?: string;
262
+ close?: (current: () => boolean, terminate?: boolean) => Promise<void>; closeScope?: () => boolean; allocation?: DirectAllocationRecord; recovery?: string;
263
263
  /** Saved sessions this task continues; claimed before any await so a second request cannot reuse them. */
264
264
  continues?: ReadonlySet<string>;
265
265
  /** Read workflows only: stop one running worker while siblings continue. */
@@ -406,7 +406,8 @@ export default function subagentExtension(pi: ExtensionAPI): void {
406
406
  await local.settled;
407
407
  // Automatic settlement may already have proved termination and released it.
408
408
  if (!current()) throw new Error("Direct task scope changed; reopen /subagent.");
409
- if (directTasks.has(task.id)) await local.close(owned);
409
+ // Only this explicit Close may signal exact lease holders; automatic settlement only proves.
410
+ if (directTasks.has(task.id)) await local.close(owned, true);
410
411
  return "All owned workers in this workflow stopped; checkout admission released. Dirty files, commits and session evidence preserved. Inspect changes before retrying work.";
411
412
  },
412
413
  async stopDirect(task, entryId, current) {
@@ -873,17 +874,17 @@ export default function subagentExtension(pi: ExtensionAPI): void {
873
874
  const proof = (async () => {
874
875
  entryControllers.get(entryId)!.abort();
875
876
  await handle.cancel().catch(() => undefined);
876
- await herdr.stop(tab, inScope);
877
+ await herdr.stop(tab, inScope, "terminate");
877
878
  })();
878
879
  stopProofs.set(entryId, proof);
879
880
  return proof;
880
881
  },
881
882
  };
882
- local.close = async (current) => {
883
+ local.close = async (current, terminate = false) => {
883
884
  const inScope = () => current() && (local.closeScope?.() ?? true);
884
885
  try {
885
886
  if (local.allocation) throw new Error(local.allocation.failure);
886
- for (const tab of tabs) await herdr.stop(tab, inScope);
887
+ for (const tab of tabs) await herdr.stop(tab, inScope, terminate ? "terminate" : "proof");
887
888
  if (!inScope()) throw new Error("Direct task scope changed; reopen /subagent.");
888
889
  releaseAdmission();
889
890
  directTasks.delete(taskId);
@@ -946,7 +947,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
946
947
  try {
947
948
  await assertSettledDirectSession(source.sessionFile, source.turn);
948
949
  // Close only an idle or done exact agent; an absent one still needs two empty lease scans.
949
- await herdr.stop(source, () => launchEpoch === sessionEpoch && !controller.signal.aborted, true);
950
+ await herdr.stop(source, () => launchEpoch === sessionEpoch && !controller.signal.aborted, "settled");
950
951
  } catch (error) {
951
952
  throw new Error(`Cannot continue ${workflow.delegations[index]!.continueFrom}: ${error instanceof Error ? error.message : String(error)}.`, { cause: error });
952
953
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "27.14.2",
3
+ "version": "27.14.3",
4
4
  "description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
5
5
  "keywords": [
6
6
  "pi-package",