@henryqw/pi-subagent 27.10.4 → 27.12.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/CONTEXT.md CHANGED
@@ -25,7 +25,7 @@ A display and continuation reference for one recorded direct worker, such as `D7
25
25
  A new direct worker that resumes a finished worker's saved Pi conversation in a new tab with a new Direct reference.
26
26
 
27
27
  **Checkout admission**:
28
- The exclusive permission held by a direct write request that prevents Main and other direct writers from writing to the shared checkout. It remains held until worker termination is proven; read classification is not a sandbox.
28
+ The exclusive permission held by a direct write request or managed background writer that prevents Main and other direct writers from writing to the shared checkout. Pi Herdr supplies the shared process-local coordinator. Each owner keeps admission until termination is proven; read classification is not a sandbox.
29
29
 
30
30
  **Isolated request**:
31
31
  A durable goal and dependency graph of text and changeset tasks, with checked results and recovery state.
@@ -67,3 +67,24 @@ Repository-scoped ownership that excludes concurrent execution or resumption whi
67
67
 
68
68
  **Safety budget**:
69
69
  A finite limit for child execution or a safety operation, not a deadline for the whole isolated request.
70
+
71
+ ## Pending-result event contract
72
+
73
+ `pi-subagent:pending-result` is an optional synchronous query through `pi.events`.
74
+ The caller emits a mutable `{ sessionId: string, pending: false }` object, then reads
75
+ `pending` when `emit` returns. Pi Subagent changes only `pending`, and only to `true`.
76
+ No listener means no pending result. Listeners must not wait for asynchronous work.
77
+
78
+ A positive answer means that this process owns live direct or isolated work for
79
+ that exact current Pi session, with a future result message that triggers a turn.
80
+ Direct ownership starts after a verified launch. Isolated ownership starts after
81
+ durable acknowledgement. Ownership ends on completion or failure, before result
82
+ delivery. Cancellation, shutdown, and session replacement cannot grant ownership.
83
+ Retained tabs, checkout admission, saved requests, interrupted or unknown work,
84
+ and results whose delivery failed do not grant ownership.
85
+
86
+ Pi Goal checks this query after its budget and continuation limits, before its
87
+ no-progress check. A positive answer lets Pi settle without another continuation
88
+ or a no-progress warning. The result message starts ordinary goal handling again.
89
+ No package dependency is required. Background-command notices do not trigger a
90
+ turn and do not participate in this contract.
package/README.md CHANGED
@@ -25,6 +25,8 @@ Configure the profiles that your Roles use in `/task-models`. Direct writer term
25
25
 
26
26
  Ask Main: “Have a scout trace sign-in without editing files.” Main calls `delegate_task` and stays available until progress and results arrive.
27
27
 
28
+ If Pi Goal is installed, it waits for live direct or isolated results in the current session instead of adding empty continuation turns. Budget and continuation limits still apply. Retained or interrupted work does not cause a wait. The optional `pi-subagent:pending-result` event needs no package dependency; see the [pending-result contract](./CONTEXT.md#pending-result-event-contract).
29
+
28
30
  Commands, prompts, and UI are for you. Tools and the packaged skill are for Main, except `git_read`, which is only for Role-declared children.
29
31
 
30
32
  | Surface | Type | Purpose |
@@ -73,6 +75,8 @@ Every task requires `access: "read"` or `access: "write"`. Declare `write` for f
73
75
 
74
76
  Read requests run parallel tasks up to `maxSubagents`. Chains run in order, replace literal `{previous}` with the preceding successful answer, and stop on failure. Any `write` task makes the whole request serial and reserves checkout admission until all owned workers stop.
75
77
 
78
+ Checkout admission is shared with managed background commands from `pi-herdr-tools`. An active or unknown background writer blocks direct writes. Main writes and direct writers block new command launches. Status and read tools remain available. This is process-local coordination, not an operating-system sandbox.
79
+
76
80
  Direct writes change Main's checkout immediately, including dirty checkouts, and have no automatic checks or rollback. Preserve unrelated edits. See [Direct contract](./docs/orchestration.md#direct-contract) for write scope and checkout-admission rules.
77
81
 
78
82
  Tasks in write requests must return one JSON completion object:
@@ -1,82 +1 @@
1
- import { realpath } from "node:fs/promises";
2
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
-
4
- // Main's own tools that never change a checkout; every other Main call may write.
5
- // `codemode` mutates nothing itself: its nested tool calls are admitted by their own names.
6
- const MAIN_NON_WRITING_TOOLS = new Set([
7
- "read", "grep", "find", "ffgrep", "fffind", "ls", "codegraph_explore", "subagent_status", "codemode",
8
- ]);
9
-
10
- async function checkoutKey(pi: ExtensionAPI, ctx: ExtensionContext): Promise<string> {
11
- const cwd = await realpath(ctx.cwd);
12
- const result = await pi.exec("git", ["rev-parse", "--show-toplevel"], { cwd, timeout: 5_000 });
13
- if (result.code !== 0 || result.killed) return cwd;
14
- const root = result.stdout.replace(/\r?\n$/, "");
15
- if (!root || /[\r\n\0]/.test(root)) throw new Error("Git returned a malformed checkout root during delegation admission.");
16
- return await realpath(root);
17
- }
18
-
19
- /**
20
- * Reserve checkouts only for direct writers. Main writes can run together, but
21
- * each call must finish before a direct writer can start in that checkout.
22
- * External processes and trusted extension lifecycle code are not intercepted.
23
- */
24
- export function registerCheckoutAdmission(pi: ExtensionAPI, directCanWrite: (input: unknown) => boolean): (toolCallId: string) => () => void {
25
- const heldCalls = new Set<string>();
26
- const ownerByCheckout = new Map<string, string>();
27
- const calls = new Map<string, { direct: boolean; key?: string }>();
28
- // One Git lookup per working directory per session; a failed lookup is retried.
29
- const checkouts = new Map<string, Promise<string>>();
30
- const lookup = (ctx: ExtensionContext) => {
31
- const cached = checkouts.get(ctx.cwd);
32
- if (cached) return cached;
33
- const key = checkoutKey(pi, ctx);
34
- checkouts.set(ctx.cwd, key);
35
- key.catch(() => { if (checkouts.get(ctx.cwd) === key) checkouts.delete(ctx.cwd); });
36
- return key;
37
- };
38
- const release = (toolCallId: string) => {
39
- if (heldCalls.has(toolCallId)) return;
40
- const call = calls.get(toolCallId);
41
- calls.delete(toolCallId);
42
- if (call?.key && ownerByCheckout.get(call.key) === toolCallId) ownerByCheckout.delete(call.key);
43
- };
44
- pi.on("tool_call", async (event, ctx) => {
45
- const direct = event.toolName === "delegate_task";
46
- if (direct ? !directCanWrite(event.input) : MAIN_NON_WRITING_TOOLS.has(event.toolName)) return;
47
- const call: { direct: boolean; key?: string } = { direct };
48
- calls.set(event.toolCallId, call);
49
- const key = await lookup(ctx);
50
- if (calls.get(event.toolCallId) !== call) {
51
- return { block: true, reason: `Call ${event.toolCallId} already settled; use mode: isolated to keep Main free.` };
52
- }
53
- const owner = ownerByCheckout.get(key);
54
- const main = direct ? [...calls].find(([, active]) => !active.direct && active.key === key)?.[0] : undefined;
55
- if (owner || main) {
56
- release(event.toolCallId);
57
- return {
58
- block: true,
59
- reason: `Checkout ${key} has ${owner ? `an admitted direct writer (${owner})` : `a Main potentially-writing call in flight (${main})`}; retry after it stops, or use mode: isolated to keep Main free.`,
60
- };
61
- }
62
- call.key = key;
63
- if (direct) ownerByCheckout.set(key, event.toolCallId);
64
- });
65
- pi.on("tool_result", (event) => release(event.toolCallId));
66
- pi.on("tool_execution_end", (event) => release(event.toolCallId));
67
- pi.on("session_start", () => checkouts.clear());
68
- pi.on("session_shutdown", () => {
69
- checkouts.clear();
70
- // Session replacement is not proof that a held direct worker stopped.
71
- for (const toolCallId of calls.keys()) release(toolCallId);
72
- });
73
- // The tool returns a handle before its worker stops. Release only after verified termination.
74
- return (toolCallId) => {
75
- const call = calls.get(toolCallId);
76
- if (!call?.direct || !call.key) {
77
- throw new Error(`Direct call ${toolCallId} was not admitted as a checkout writer; delegate again.`);
78
- }
79
- heldCalls.add(toolCallId);
80
- return () => { heldCalls.delete(toolCallId); release(toolCallId); };
81
- };
82
- }
1
+ export { registerCheckoutAdmission } from "@henryqw/pi-herdr";
@@ -514,6 +514,7 @@ export function formatExecutePlan({ request, root, main, routes }: ExecutePlan,
514
514
  }
515
515
 
516
516
  export interface IsolatedSurface {
517
+ hasPendingResult(sessionId: string): boolean;
517
518
  /** Dry run of execute: validates and resolves without durable state or Herdr calls. */
518
519
  plan(request: ExecuteRequest, signal: AbortSignal | undefined, ctx: ExtensionContext): Promise<ReturnType<typeof formatExecutePlan>>;
519
520
  execute(request: ExecuteRequest, signal: AbortSignal | undefined, ctx: ExtensionContext): Promise<ReturnType<typeof toolResult>>;
@@ -547,7 +548,7 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
547
548
  let savedRevision = 0;
548
549
  const stateListeners = new Set<(state: RunState) => void>();
549
550
  const activeJobs = new Set<AbortController>();
550
- const jobOwners = new Map<string, () => boolean>();
551
+ const jobOwners = new Map<string, { canDeliver(): boolean; pendingResult(): boolean }>();
551
552
  let sessionEpoch = 0;
552
553
  let sessionClosed = false;
553
554
 
@@ -570,7 +571,7 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
570
571
  savedRevision += 1;
571
572
  for (const listener of stateListeners) listener(state);
572
573
  const owner = jobOwners.get(`${state.root}\0${state.request.id}`);
573
- if (!sessionClosed && (owner === undefined || owner())) {
574
+ if (!sessionClosed && (owner === undefined || owner.canDeliver())) {
574
575
  updateWorkspaceWidgetSafely(latestContext(), state, workspaceRowsByRequest);
575
576
  }
576
577
  },
@@ -632,21 +633,22 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
632
633
  : undefined;
633
634
  const canDeliver = () => deliverySuppression() === undefined;
634
635
  const controller = new AbortController();
636
+ let durableAcknowledged = false;
635
637
  activeJobs.add(controller);
636
- jobOwners.set(key, canDeliver);
638
+ const owner = { canDeliver, pendingResult: () => durableAcknowledged && !controller.signal.aborted && canDeliver() };
639
+ jobOwners.set(key, owner);
637
640
  const notified = new Set<string>();
638
641
  const attentionNotified = new Set<string>();
639
642
  let candidateListener: ((state: RunState) => void) | undefined;
640
643
  const finish = () => {
641
644
  activeJobs.delete(controller);
642
645
  if (candidateListener) stateListeners.delete(candidateListener);
643
- if (jobOwners.get(key) === canDeliver) jobOwners.delete(key);
646
+ if (jobOwners.get(key) === owner) jobOwners.delete(key);
644
647
  };
645
648
  const abortBeforeAck = () => controller.abort(signal?.reason);
646
649
  if (signal?.aborted) abortBeforeAck();
647
650
  else signal?.addEventListener("abort", abortBeforeAck, { once: true });
648
651
  let latestState: RunState | undefined;
649
- let durableAcknowledged = false;
650
652
  let accept!: (state: RunState) => void;
651
653
  let reject!: (error: unknown) => void;
652
654
  const durable = new Promise<RunState>((resolve, fail) => { accept = resolve; reject = fail; });
@@ -828,6 +830,8 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
828
830
  },
829
831
  });
830
832
  return {
833
+ hasPendingResult: (sessionId) => latestCtx?.sessionManager?.getSessionId() === sessionId
834
+ && [...jobOwners.values()].some((owner) => owner.pendingResult()),
831
835
  async inventory(cwd, current) {
832
836
  const root = await lookupRoot(cwd);
833
837
  const revision = savedRevision;
@@ -256,6 +256,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
256
256
  let directSequence = 0;
257
257
  const directTasks = new Map<string, {
258
258
  controller: AbortController; settled: Promise<void>; handles: DirectHandle[]; tabs: DirectTabRecord[];
259
+ pendingResult?: (sessionId: string) => boolean;
259
260
  close?: (current: () => boolean) => Promise<void>; closeScope?: () => boolean; allocation?: DirectAllocationRecord; recovery?: string;
260
261
  /** Saved sessions this task continues; claimed before any await so a second request cannot reuse them. */
261
262
  continues?: ReadonlySet<string>;
@@ -268,6 +269,14 @@ export default function subagentExtension(pi: ExtensionAPI): void {
268
269
  && tab.paneId === saved.paneId && tab.sessionFile === saved.sessionFile;
269
270
  });
270
271
  let sessionEpoch = 0;
272
+ pi.events.on("pi-subagent:pending-result", (data) => {
273
+ if (!data || typeof data !== "object" || !("sessionId" in data) || typeof data.sessionId !== "string"
274
+ || !("pending" in data) || typeof data.pending !== "boolean") return;
275
+ const { sessionId } = data;
276
+ if ([...directTasks.values()].some((task) => task.pendingResult?.(sessionId)) || isolatedSurface.hasPendingResult(sessionId)) {
277
+ data.pending = true;
278
+ }
279
+ });
271
280
  // Shutdown still saves outgoing identities; only a session start defers records to its carry loop.
272
281
  let directRecordEpoch = 0;
273
282
  let directWorkflow = 0;
@@ -767,6 +776,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
767
776
  });
768
777
  const controller = new AbortController();
769
778
  const launchEpoch = sessionEpoch;
779
+ const launchSessionId = ctx.sessionManager.getSessionId();
770
780
  const recordEpoch = directRecordEpoch;
771
781
  const handles: DirectHandle[] = [];
772
782
  const tabs: DirectTabRecord[] = [];
@@ -887,6 +897,9 @@ export default function subagentExtension(pi: ExtensionAPI): void {
887
897
  resolveSettled();
888
898
  throw boundedError(error);
889
899
  } finally { signal?.removeEventListener("abort", abortLaunch); }
900
+ local.pendingResult = (sessionId) => !controller.signal.aborted && launchEpoch === sessionEpoch
901
+ && sessionId === launchSessionId && ctx.sessionManager.getSessionId() === launchSessionId
902
+ && latestCtx?.sessionManager.getSessionId() === launchSessionId;
890
903
  void (async () => {
891
904
  try {
892
905
  await new Promise<void>((resolve) => setImmediate(resolve));
@@ -944,6 +957,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
944
957
  try { await local.close!(() => directTasks.get(taskId) === local); }
945
958
  catch { /* Retain ownership and admission for an explicit guarded retry. */ }
946
959
  } else directTasks.delete(taskId);
960
+ local.pendingResult = undefined;
947
961
  if (!controller.signal.aborted) reportDirect(launchEpoch, taskId, ref, workflow.mode, [...states.values()], tabs, local.recovery);
948
962
  resolveSettled();
949
963
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "27.10.4",
3
+ "version": "27.12.0",
4
4
  "description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -71,7 +71,7 @@
71
71
  },
72
72
  "dependencies": {
73
73
  "@henryqw/pi-config-store": "^4.0.0",
74
- "@henryqw/pi-herdr": "^0.5.0",
74
+ "@henryqw/pi-herdr": "^0.6.0",
75
75
  "@henryqw/pi-multi-codex": "^3.0.0",
76
76
  "@henryqw/pi-process": "^0.2.0",
77
77
  "@henryqw/pi-task-models": "^9.0.0",