@henryqw/pi-herdr 0.6.0 → 0.6.2

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
@@ -56,6 +56,16 @@ Errors expose `code` and `dispatched`. If `dispatched` is true, a mutation can h
56
56
 
57
57
  `registerCheckoutAdmission(pi, directCanWrite)` keeps the direct-subagent policy: Main writes can overlap, but direct writers must wait for them and exclude other writes. A returned hold function keeps a direct request admitted beyond its tool result. Consumers must restore durable command ownership before allowing writes after restart. These mechanisms do not intercept external processes or provide a sandbox.
58
58
 
59
+ An optional third argument, `directCheckouts(input, ctx)`, returns additional canonical checkout paths for a direct request. Admission reserves the current checkout and the complete selected set together. A conflict in one member blocks the request without a partial reservation. The caller validates repository selection; the hold function releases the set only after caller-proved worker termination.
60
+
61
+ ### Path locks
62
+
63
+ `withWorktreeLock(checkout, operation)` locks a path while the operation runs. Acquisition, heartbeat updates, and release use synchronous filesystem calls. Slow storage can block the event loop. The operation can remain asynchronous. A heartbeat cannot remain in flight when the helper releases the lock.
64
+
65
+ If a heartbeat detects lost ownership, the call rejects after the operation finishes and does not release the changed lock. If the operation also fails, an `AggregateError` contains both errors. Acquisition, operation, and release errors remain visible. The helper does not stop or undo the operation.
66
+
67
+ Heartbeats do not prove continuous ownership or detect all external lock removal or replacement between checks. Do not remove active lock files. Long event-loop pauses can delay heartbeats and permit stale-lock recovery by another process. A lock error does not prove that the operation had no effect. Inspect state before a retry.
68
+
59
69
  ### `startPiAgent`
60
70
 
61
71
  On macOS, a shell that starts or runs a prompt hook can lose Enter for a launch command longer than 1024 bytes. The pane then waits forever. To prevent this, the helper first checks `pane process-info`. When the pane shell owns the foreground process group, it runs `pane run <pane> "echo <token>"` and polls `pane read` for up to 20 seconds. The probe passes when the token appears on its own line, with a prompt after it.
@@ -37,7 +37,10 @@ export declare function checkoutKey(pi: Pick<AdmissionHost, "exec">, ctx: {
37
37
  declare function createAdmission(): {
38
38
  install: (host: AdmissionHost) => void;
39
39
  hold: (toolCallId: string) => () => void;
40
- classifyDirect: (classify: (input: unknown) => boolean) => void;
40
+ supportsCheckoutSets: true;
41
+ classifyDirect: (classify: (input: unknown) => boolean, select?: ((input: unknown, ctx: {
42
+ cwd: string;
43
+ }) => Promise<readonly string[]>) | undefined) => void;
41
44
  guard: (name: string, refresh: () => Promise<void>) => void;
42
45
  restore: (owner: string, checkout: string) => void;
43
46
  release: (owner: string) => void;
@@ -46,5 +49,7 @@ declare function createAdmission(): {
46
49
  export type CheckoutAdmission = ReturnType<typeof createAdmission>;
47
50
  /** Share admission through Pi's public event bus; its per-extension facades have distinct identities. */
48
51
  export declare function checkoutAdmission(pi: AdmissionHost): CheckoutAdmission;
49
- export declare function registerCheckoutAdmission(pi: AdmissionHost, directCanWrite: (input: unknown) => boolean): (toolCallId: string) => () => void;
52
+ export declare function registerCheckoutAdmission(pi: AdmissionHost, directCanWrite: (input: unknown) => boolean, directCheckouts?: (input: unknown, ctx: {
53
+ cwd: string;
54
+ }) => Promise<readonly string[]>): (toolCallId: string) => () => void;
50
55
  export {};
package/dist/admission.js CHANGED
@@ -22,6 +22,7 @@ export async function checkoutKey(pi, ctx) {
22
22
  */
23
23
  function createAdmission() {
24
24
  let directCanWrite = (_input) => true;
25
+ let directCheckouts;
25
26
  const guards = new Map();
26
27
  const durable = new Map();
27
28
  const events = new WeakMap();
@@ -45,8 +46,9 @@ function createAdmission() {
45
46
  return;
46
47
  const call = calls.get(toolCallId);
47
48
  calls.delete(toolCallId);
48
- if (call?.key && ownerByCheckout.get(call.key) === toolCallId)
49
- ownerByCheckout.delete(call.key);
49
+ for (const key of call?.keys ?? [])
50
+ if (ownerByCheckout.get(key) === toolCallId)
51
+ ownerByCheckout.delete(key);
50
52
  };
51
53
  const refresh = async () => { for (const guard of guards.values())
52
54
  await guard(); };
@@ -62,22 +64,30 @@ function createAdmission() {
62
64
  }
63
65
  const call = { direct };
64
66
  calls.set(event.toolCallId, call);
65
- const key = await lookup(host, ctx);
67
+ let keys;
68
+ try {
69
+ keys = [...new Set([await lookup(host, ctx), ...(direct && directCheckouts ? await directCheckouts(event.input, ctx) : [])])];
70
+ }
71
+ catch (error) {
72
+ release(event.toolCallId);
73
+ throw error;
74
+ }
66
75
  if (calls.get(event.toolCallId) !== call) {
67
76
  return { block: true, reason: `Call ${event.toolCallId} already settled; use mode: isolated to keep Main free.` };
68
77
  }
69
- const owner = ownerByCheckout.get(key) ?? [...durable].find(([, checkout]) => checkout === key)?.[0];
70
- const main = direct ? [...calls].find(([, active]) => !active.direct && active.key === key)?.[0] : undefined;
78
+ const owner = keys.map((key) => ownerByCheckout.get(key) ?? [...durable].find(([, checkout]) => checkout === key)?.[0]).find(Boolean);
79
+ const main = direct ? [...calls].find(([, active]) => !active.direct && active.keys?.some((key) => keys.includes(key)))?.[0] : undefined;
71
80
  if (owner || main) {
72
81
  release(event.toolCallId);
73
82
  return {
74
83
  block: true,
75
- 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.`,
84
+ reason: `Checkout set ${keys.join(", ")} 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.`,
76
85
  };
77
86
  }
78
- call.key = key;
87
+ call.keys = keys;
79
88
  if (direct)
80
- ownerByCheckout.set(key, event.toolCallId);
89
+ for (const key of keys)
90
+ ownerByCheckout.set(key, event.toolCallId);
81
91
  };
82
92
  const install = (host) => {
83
93
  host.on("tool_call", (event, ctx) => {
@@ -99,15 +109,15 @@ function createAdmission() {
99
109
  };
100
110
  const hold = (toolCallId) => {
101
111
  const call = calls.get(toolCallId);
102
- if (!call?.direct || !call.key) {
112
+ if (!call?.direct || !call.keys?.length) {
103
113
  throw new Error(`Direct call ${toolCallId} was not admitted as a checkout writer; delegate again.`);
104
114
  }
105
115
  heldCalls.add(toolCallId);
106
116
  return () => { heldCalls.delete(toolCallId); release(toolCallId); };
107
117
  };
108
118
  return {
109
- install, hold,
110
- classifyDirect: (classify) => { directCanWrite = classify; },
119
+ install, hold, supportsCheckoutSets: true,
120
+ classifyDirect: (classify, select) => { directCanWrite = classify; directCheckouts = select; },
111
121
  guard: (name, refresh) => { guards.set(name, refresh); },
112
122
  restore: (owner, checkout) => { durable.set(owner, checkout); },
113
123
  release: (owner) => { durable.delete(owner); },
@@ -115,7 +125,7 @@ function createAdmission() {
115
125
  await refresh();
116
126
  const conflict = [...durable].find(([, key]) => key === checkout)?.[0]
117
127
  ?? ownerByCheckout.get(checkout)
118
- ?? [...calls].find(([, call]) => call.key === checkout)?.[0];
128
+ ?? [...calls].find(([, call]) => call.keys?.includes(checkout))?.[0];
119
129
  if (conflict)
120
130
  throw new Error(`Checkout ${checkout} has an active writer (${conflict}); wait until it stops.`);
121
131
  durable.set(owner, checkout);
@@ -137,9 +147,14 @@ export function checkoutAdmission(pi) {
137
147
  });
138
148
  return shared;
139
149
  }
140
- export function registerCheckoutAdmission(pi, directCanWrite) {
150
+ export function registerCheckoutAdmission(pi, directCanWrite, directCheckouts) {
141
151
  const admission = checkoutAdmission(pi);
142
- admission.classifyDirect(directCanWrite);
152
+ admission.classifyDirect((input) => {
153
+ if (directCanWrite(input) && admission.supportsCheckoutSets !== true && input && typeof input === "object" && Object.hasOwn(input, "repositories")) {
154
+ throw new Error("The active checkout coordinator does not support repository sets. Reload with the current Pi Herdr package before delegation.");
155
+ }
156
+ return directCanWrite(input);
157
+ }, directCheckouts);
143
158
  admission.install(pi);
144
159
  return admission.hold;
145
160
  }
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { lock } from "proper-lockfile";
1
+ import { lockSync } from "proper-lockfile";
2
2
  export { requestHerdr, HerdrRequestError } from "./socket.js";
3
3
  export { checkoutAdmission, checkoutKey, registerCheckoutAdmission } from "./admission.js";
4
4
  const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
@@ -139,12 +139,24 @@ export function hasHerdrErrorCode(result, expected) {
139
139
  }
140
140
  /** Lock a Herdr worktree checkout path while mutating it via the Herdr CLI. */
141
141
  export async function withWorktreeLock(checkout, operation) {
142
- const release = await lock(checkout);
142
+ let compromised;
143
+ // Synchronous heartbeats cannot remain in flight when release removes the lock.
144
+ const release = lockSync(checkout, { onCompromised: (error) => { compromised = error; } });
143
145
  try {
144
- return await operation();
146
+ const result = await operation();
147
+ if (compromised)
148
+ throw compromised;
149
+ return result;
150
+ }
151
+ catch (error) {
152
+ if (compromised && error !== compromised)
153
+ throw new AggregateError([error, compromised], "Operation failed and lock ownership was lost.");
154
+ throw error;
145
155
  }
146
156
  finally {
147
- await release();
157
+ // A compromised lock is no longer ours to release.
158
+ if (!compromised)
159
+ release();
148
160
  }
149
161
  }
150
162
  function herdrCommandName(args) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-herdr",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Shared client for interacting with Herdr from Node.js tools and Pi packages.",
5
5
  "keywords": [
6
6
  "pi-package",